RonnyKnoxville
RonnyKnoxville

Reputation: 6394

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?

Upvotes: 3

Views: 1491

Answers (2)

Sparky
Sparky

Reputation: 98718

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.

Upvotes: 1

RonnyKnoxville
RonnyKnoxville

Reputation: 6394

As a workaround, I came up with the following code to check the pattern attribute and set a custom message during validator.addMethod().

$o.validator.addMethod("regex", function(value, element){
  var pattern = $o(element).prop('pattern');
  if(!pattern || this.optional(element)){
    return true;
  }
  return new RegExp(pattern).test(value);
}, $o.validator.format("{0}"));

$o.validator.addClassRules("visible-postcode-input", {
  regex: "Please enter a valid UK postcode",
});

Upvotes: 0

Related Questions