4

I`m using jQuery form validation plugin and and use regex to validate one field. Here is some code:

$.validator.addMethod('regex',
            function(value, element, regexp) {
            var check = false;
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
             },
    "" );    

<input id="school" name="school" type="text" style="float: left" />

$("#school").rules("add", { regex: "^[a-zA-Z0-9]*$"});

But I want to use \ and ] symbols in this field. Escaping these characters with backslashes doesn`t help, even with 3 or 4 backslashes as mentioned here

Edited
Thanks. It was really my mistake. I updated regex to validate different symbols (also backslash and ] )

$("#school").rules("add", { regex: /^[a-zA-Z0-9\',!;\<>\?\$\^:\\\/`\|~&\" @#%\*\{}\(\)\[\]_\+\.\s=-]*$/ }); 

it works now.

Community
  • 1
  • 1
Iurii Dziuban
  • 1,091
  • 2
  • 17
  • 31

1 Answers1

1

This one should work:

'^[a-zA-Z0-9\\]\\\\]*$'

Two backlashes before ] gives one backslash in final string, and this backslash escapes ] sign. Four backslashes produces two backslashes (two escaped backslashes) in final string, and this two backlashes passed to RegExp constructor gives one escaped backslash.

Here is simple demo: http://jsfiddle.net/CsQn7/1/

Mateusz W
  • 1,981
  • 1
  • 14
  • 16