Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate regex in HTML5

Im using jQuery validate to validate a front end form. I ideally want the regex to be picked up from the HTML5 pattern attribute on the input field.

I have a working version using the following code:

function isUKPostcode(value){
  return /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/.test(value);
}

$.validator.addMethod("postcode", function(value, element){
  return this.optional(element) || isUKPostcode(value);
}, "Please enter a valid UK postcode");

But ideally I would like to set it up with simply:

<input id="Inputfield_user_first_name" class="postcode" name="user_first_name" type="text" maxlength="60" pattern="([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)">

The same way that attributes such as required and maxlength are automatically picked up by $.validate()

Does anyone know if this is possible?

like image 557
RonnyKnoxville Avatar asked Apr 26 '26 14:04

RonnyKnoxville


1 Answers

There is no need to write a custom method.

You simply need to include the additional-methods.js file. It includes the pattern method which will pickup the HTML5 pattern attribute automatically.

like image 111
Sparky Avatar answered Apr 29 '26 05:04

Sparky