denying special characters jQuery Validate

29,863

rather than testing for the presence of the special characters, test for only presence of valid characters

regex: /^[A-Za-z\d=#$%...-]+$/

Replace ... with all the special characters you want to allow. In the example above, #, $, %, and - would be allowed. Note: you don't have to escape (most) of the characters inside of the [].

If you'd like to allow a -, it needs to be the last character otherwise regex tries to parse a range. (e.g., [a-c] matches a, b, and c. [a-c-] matches a, b, c, and -)

Also, if you'd like to allow a ^, it cannot be the first character otherwise regex treats this as a sort of not operator. (e.g., [^abc] matches any character that's not a, b, or c)


In your example above, the complete regex might look something like this

regex: /^[A-Za-z\s`~!@#$%^&*()+={}|;:'",.<>\/?\\-]+$/

Explanation

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [A-Za-                   any character of: 'A' to 'Z', 'a' to 'z',
  z\s`~!@#$%^&*()+={}|     whitespace (\n, \r, \t, \f, and " "), '`',
  ;:'",.<>/?\\-]+          '~', '!', '@', '#', '$', '%', '^', '&',
                           '*', '(', ')', '+', '=', '{', '}', '|',
                           ';', ':', ''', '"', ',', '.', '<', '>',
                           '/', '?', '\\', '-' (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

check it out!

Share:
29,863
Mario
Author by

Mario

Updated on February 16, 2020

Comments

  • Mario
    Mario about 4 years

    I need to validate a textarea using the plugin jQuery Validate, to do that I use a regex and I add a method to the plugin:

    $.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var check = false;
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "No special Characters allowed here. Use only upper and lowercase letters (A through Z; a through z), numbers and punctuation marks (. , : ; ? ' ' \" - = ~ ! @ # $ % ^ & * ( ) _ + / < > { } )"
    );
    

    Then in the options I add the regex:

    comments:{
        required: true,
        maxlength: 8000,
        regex: /[^A-Za-z\d\-\=\~\!@#\%&\*\(\)_\+\\\/<>\?\{\}\.\$‘\^\+\"\';:,\s]/
    }
    

    This "works" in a certain way, it does detect the invalid characters and displays the message, the problem is it only works when the special characters are the only ones in the box, for instance:

    | `` ° ¬ // This shows the error message but...
    test | // This won't show the message
    

    So if one allowed character is there then the validation just stops working. Am I missing something?

    P.S. I'm pretty sure this has something to do with the plugin 'cause I've tested the regex with just javascript and it works well.

  • Mario
    Mario over 12 years
    Thanks man, this really helped me (I've been struggling for days -.-). Just for the record, there was a little mistake in your code, you forgot to escape the slash. Or am I wrong?
  • maček
    maček over 12 years
    Ah yes, the / should be escape because it matches the delimiter.
  • SoldierCorp
    SoldierCorp almost 12 years
    And without whitespace, how will be?
  • maček
    maček almost 12 years
    @SoldierCorp, just remove the \s