1

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?

4
  • 1
    You need to add anchors: ^[-A-Za-z0-9 ]+$. Additionally, it is always wise to put the dash at the beginning as it has different meanings in a character class. Commented Aug 15, 2016 at 11:55
  • Specifically /^[-A-Za-z0-9 ]+$/, add as answer if you like? Commented Aug 15, 2016 at 11:58
  • 1
    Done that - did it work ? :) Commented Aug 15, 2016 at 11:59
  • Yep, had to wait 7 minutes. Commented Aug 15, 2016 at 12:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.