$.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.
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.");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With