Customize form validation by using jQuery validation plugin

Sometime form validation is trouble thing for building the front page, in this article briefing a method which allow us to customize the validation by adding ourselves’ rule through jQuery validation plugin, it’s friendly to mobile version.

First, include necessary dependencies in html code:

In order to make sure the page is responsive on mobile device, we need to add basic mata data in head of html.

Second, create simple form:

Now, the page looks like:

form1

We have to add some javascript code to trigger the validation engine once the form is submitted.

we use the basic setting to do basic validation, in this example, first name, last name, email, NRIC/FIN and mobile phone number is required, and email element is build-in detection in the validation plugin. Click submit button without anything entered will get result as below:

form2

The question is we want to validate NRIC/FIN and Mobile phone with Singapore format rule which is:

  • NRIC/FIN: must be 9 length, prefix with G,F,T or S and following by 7 digital numbers and end with a check digit and its checking algorithm as below:form3
    we can define a function to do the checking, this is another problem.
  • Mobile phone number must be in 8 digit numbers.

jQuery validation plugin allow to add customized rule like below:

finSG:true is the customized check function, that mean we can define a method somewhere to help to do checking work.

jQuery.validator.addMethod function accept 3 parameters: name,function and message:

function CheckDigit(fin_number) is another function that we can define some where, also can be included inside, it just return true or false.

final code:

Tagged with: ,
Posted in HTML5, Javascript

Leave a Reply

Categories

Related Posts