Manu Torres
Manu Torres

Reputation: 68

How to validate a field that is not required with a regex with JQuery

I have a form in my web and I'm using the JQuery validation plugin. I have a 'comment' that I want to be NOT required (it can be empty), but has to match a specific regular expression if filled.

Using this, if the field is empty, the validation returns false (not valid), and the error is shown:

'comment':{
     required: false,
     regexp: /^([-a-z0-9_ ()])+$/i,
},

How can I achieve the intended behaviour?

Upvotes: 1

Views: 2841

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

Try:

/^[-a-z0-9_ ()]+$|^$/i

I just added another match for emptiness

Upvotes: 3

Related Questions