user1063287 user1063287 - 1 year ago 149
jQuery Question

Regex for Validetta jQuery plugin

I am validating an input field with the Validetta jQuery plugin (regex demo).

I want to allow numbers, letter, spaces and dashes.

I'm trying to create the correct regex for the Validetta parameters:

validators: {
regExp: {
regname : {
pattern : [pattern here]
errorMessage : 'Only numbers, letters, spaces and dashes allowed'
}
}
}


Here is a link to a regex tester with prefilled regex and results:

http://regexr.com/3e10d

It seems to be matching everything I want it to match.

It provides the regex in three formats:

Expression:
/([A-Z0-9 -])/ig


Pattern:
([A-Z0-9 -])


Javascript:
text.match(/([A-Z0-9 -])/ig);


These are not having the desired effect when used in Validetta, eg:

pattern : /([A-Z0-9 -])/ig,


This validates:
web's test


This doesn't:
'web


OR:

pattern : ([A-Z0-9 -]),


Causes page not to load with Firebug error:


// SyntaxError: expected expression, got ']'


What pattern should I be using in Validetta to get the desired results?

Jan Jan
Answer Source

As said in the comments, you probably want:

^[-A-Za-z0-9 ]+$

Note the dash in the beginning as well as the anchors which will only allow the specified characters in the class from the beginning to the end.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download