3

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?

1
  • 4
    Remove $ from the pattern, HTML5 don't need the ^ and $ anchors Commented Nov 27, 2015 at 10:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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",
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.