I want to be able to validate a Postcode by matching a regular expression (using this script). There is no default option with this jQuery script to do so. My question is can I add such a custom regex to this script?
I have only ever written validation in “normal” JS before so any help much appreciated. Also I would like the JS regex to match the existing one serverside (PHP):
I would like to add another regular expression, this time to a different field. I would like to check for a valid UK telephon number.
So far this is the jQuery :-
$(document).ready(function(){
//Set Fields to be validated
$("#EventForm").validate();
$( "#StartDate" ).datepicker();
$( "#EndDate" ).datepicker();
//Add Postcode Regex Method to Validator Function
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please enter a valid postcode."
);
//Add Postcode Regular Expression Rule to Postcode Field
$("#EventPostcode").rules("add", { regex: "^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$"});
});
This checks for valid postcodes and works great. But how would I go about adding a rule for another field, e.g. “#mytelephonenumber” ?
Your existing added method, instead of calling it “regex” I suggest you call it something like “postcode” instead. That way you can add a different but similar method called function called “telephone”, which performs a similar regex check and provides an appropriate error message.
Ok, I have added the new method rules fine. But im trying to use this Reg Ex:
And firebug is telling me “invalid quantifier” Does anyone have any idea why this is happening?
My code:
//Add Postcode Regex Method to Validator Function
$.validator.addMethod(
"postcode",
function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please enter a valid postcode."
);
//Add UK Telephone number Regex Method to Validator Function
$.validator.addMethod(
"telephone",
function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please enter a valid UK telephone number in the format - 01856 666666."
);
//Add Postcode Regular Expression Rule to Postcode Field
$("#EventPostcode").rules("add", { postcode: "^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$"});
$("#EventTelephoneNo").rules("add", { telephone: "(\\s*\\(?0\\d{4}\\)?(\\s*|-)\\d{3}(\\s*|-)\\d{3}\\s*)|(\\s*\\(?0\\d{3}\\)?(\\s*|-)\\d{3}(\\s*|-)\\d{4}\\s*)|(\\s*(7|8)(\\d{7}|\\d{3}(\\-|\\s{1})\\d{4})\\s*)"});