1
'^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$'

the above regular expression accepts inputs like T3K2H3 or T3K-2H3 from .net form but when i run the validation through the javascript; it does not work.

var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$');

var postalCode = 't3k2h3';

var matchesPostalCode = rxPostalCode.exec(postalCode);

if (matchesPostalCode == null || postalCode != matchesPostalCode[0]) {

    $scope.AccountInfoForm.PostalCode.$setValidity("pattern", false);

    $scope.showLoading = false;

    return false;
}
donfuxx
  • 11,277
  • 6
  • 44
  • 76
MG3478291
  • 27
  • 3

4 Answers4

0

I believe that in javascript, you have to do // instead of ''

as follows:

/^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$/

You might want to check the following link:

Validate email address in JavaScript?

Community
  • 1
  • 1
sshashank124
  • 31,495
  • 9
  • 67
  • 76
0

You have two syntaxes to define a regexp object:

var rxPostalCode = /^[abceghj-np-tvxy]\d[abceghj-np-tv-z][ -]?\d[abceghj-np-tv-z]\d$/i;

or

var rxPostalCode = new RegExp('^[abceghj-np-tvxy]\\d[abceghj-np-tv-z][ -]?\\d[abceghj-np-tv-z]\\d$',  'i');

Note that with the second syntax you need to use double backslashes.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

Try the following pattern:

^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz][ -]*\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]\d

Remove the $ at the end and see if that solves your problem.

I also simplified things a bit, the \d{1} is the same as \d

I would also change the [ -]* to [ -]? unless you want to allow multiple spaces or dashes

I suspect what is happening is that the $ expect the end of the line or string, and JavaScript may not store the VAR properly. See if remove the $ solves it, or possibly keeping the $ and trim() the string.

Sparky
  • 14,967
  • 2
  • 31
  • 45
0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

"Do not forget to escape \ itself while using the RegExp("pattern") notation because \ is also an escape character in strings."

var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\\d{1}$');

That should work, I tested it in Chrome's console.

Jason Pearson
  • 609
  • 4
  • 15