Jquery Regex Validation

A quick post about validating anything you want using regex. I used it in a project that created forms on the fly, so validations like email, numbers and so on wasn’t so simple (I couldn’t do it by just adding the validation as a class: class=”email”)

so first step is adding what we need before the </head>:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validate.pack.js">

now just after the above code we add our regex method:

<script type="text/javascript">
$.validator.addMethod(
 "regex",
 function(value, element, regexp) {
 var check = false;
 var re = new RegExp(regexp);
 return this.optional(element) || re.test(value);
 },
 "Please check your input"
);
</script>

and the final thing is ading the validation we need – you can use php to add them from the database for instance:

<script type="text/javascript">
$(document).ready(function(){ 
$("#myFieldId").rules("add", {regex: "^(0|[1-9][0-9]*|[1-9][0-9]{0,2}(,[0-9]{3,3})*)$"});
})
</script>