1

Basically what i am trying to do is validate a form. In one of the fields i want to allow spaces:

I've been using:

$.validator.addMethod(
    "legalname",
    function(value, element) {
        return this.optional(element) || /^[a-zA-Z0-9()._-\s]+$/.test(value);
    },
    "Illegal character. Only points, spaces, underscores or dashes are allowed."
);

$("#editform").validate({
    rules: {
        name: {
            required: true,
            legalname: true
        },
    });

This works in Safari, but not in Firefox where it gives me a "invalid range in character class". Any ideas how i can get this working?

7
  • 1
    Escape that dash. Within a character class it defines a character range. Commented Jun 24, 2012 at 8:14
  • @RayToal. My thoughts exactly. +1 Commented Jun 24, 2012 at 8:15
  • You're missing a } on the validate(), and older versions of IE can flip out over trailing commas like the one below name:. Commented Jun 24, 2012 at 8:16
  • Or the OP could put the dash at the end. Interesting about it "working in Safari," eh? Commented Jun 24, 2012 at 8:17
  • 1
    @gdoron it's safe to put the dash at the beginning or end of a character class, Sections 15.10.1 and 15.10.2 of the ECMAScript 5 spec define how it works. But good point about it being risky in the sense of a possible later modification shifting its position. Best to explicitly escape the dashes and right brackets at all times, perhaps. Commented Jun 24, 2012 at 8:29

1 Answer 1

4

Try escaping the -: As you can see here: Working demo: http://jsfiddle.net/svp6D/2

/^[a-zA-Z0-9()._\-\s]+$/

Characters that need to be escaped inside characters class ([]) are:

- \ / [] ^
Sign up to request clarification or add additional context in comments.

4 Comments

<boom> ++1; Yo, can I take initiative and make minor addition to your post plz?
@Tats_innit. You can do that with asking. I trust you, (And I get notification why my posts were changed so I can review them...)
I don't know how the rest of you feel, but I find regular-expressions.info a good resource.
@gdoron added a working demo of your solution, works like a rocket to mars! :)

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.