Checking NI JQuery Number

$.validator.addMethod(
    "ninumber",
    function(value, element) {
        return this.optional(element)
          || /^[A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}[0-9]{6}[A-DFM]{0,1}$/.test(value);
    },
    "Please enter a valid NI Number."
);

Can anyone identify any problems with the sample code? It seems to me that this is good, but the correct values ​​are still displayed as having an error. I am using the jQuery Validation plugin to add a method for the NI number.

+3
source share
1 answer

This does not allow spaces, so you need to remove them first. I just checked and checks my NI number, but only without spaces.

So you need something like:

/^[A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}[0-9]{6}[A-DFM]{0,1}$/.test(value.replace(/\s/g, ''));

if you really want to keep it in a single line check. Personally, I reformatted / reorganized:

$.validator.addMethod("ninumber", function(value, element) {
  var regexp = /^[A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}[0-9]{6}[A-DFM]{0,1}$/;
  var strippedValue = value.replace(/\s/g, '');
  return this.optional(element) || regexp.test(strippedValue);
},  "Please enter a valid NI Number.");
+3
source

All Articles