Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NI Number Validation Jquery

$.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 spot any issues with the code sample? It seems fine to me, yet the correct values are still showing as having an error. I'm using the jQuery Validation plugin to add the method for NI Number.

like image 471
Rachel Avatar asked Apr 30 '26 10:04

Rachel


1 Answers

It doesn't allow for spaces, so you need to strip those first. I've just checked and it validates my NI number, but only without spaces.

So, you'd want 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 wanted to keep it to a one-line validation. Personally, I'd reformat/refactor:

$.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.");
like image 87
Skilldrick Avatar answered May 02 '26 06:05

Skilldrick