Forms Validation--javascript and jquery editions

Source: Internet
Author: User

1. Lightweight JavaScript Form validation

Referencing files in your app validator.min.js

<script type= "Text/javascript" src= "Dist/validator.min.js" ></script>

Instance:

<form id= "Example_form" > <div> <label for= "Email" > Email verification </label> <input type= "email" name= "email" id= "email" class= "Form-control" placeholder= "Ema Il "> </div></form><script type=" Text/javascript ">varValidator =NewValidator (' Example_form ',[    {        //Name FieldName: ' Email ', display:"You typed no {{email}} is a legitimate mailbox | cannot be empty | too long | Too short",        //Validation CriteriaRules: ' Is_emil|max_length (|required) '//rules: ' Valid_email|required|max_length (|min_length) (2) '    },{        //Name FieldName: ' Sex ', display:"Please choose gender {{sex}}",        //Validation CriteriaRules: ' Required '    }  ],function(obj,evt) {if(obj.errors) {//Judging whether it is wrong      }  })</script>

Description

New Validator (formName, option, callback)
FormName

formNameis the <form> value in the id tag name , as in the aboveexample_form

Option
    • namenamethe corresponding value in input
    • display--validation error text to prompt{{这个中间是name对应的值}}
    • rulesOne or more rules (intermediate | interval)

      • is_emailAuthentication Legal Mailbox
      • is_ipAuthentication Legal IP Address
      • is_faxAuthentication Fax
      • is_tel--Verification landline
      • is_phone--Authentication Phone
      • is_urlAuthentication URL
      • requiredis required
      • max_length-Max character length
      • min_length-min. character length
Custom Regular

Customize the regular to regexp_ start

{  //Name field  name: ' Sex ',// correspondingto the   following authentication prompt information  Display: "Please choose gender {{sex}}| Please enter number"  ,// custom Regular ' regexp_num '  regexp_num:/^[ 0-9]+$/,  //  validation conditions, including application of custom regular ' Regexp_num '  rules: ' Required|regexp_num ' }

String Validation:

varv =NewValidator (); V.isemail (' [email protected] ';//-- Authentication Legal mailbox |=> Returns a Boolean valueV.isip (' 192.168.23.3 ');//-- Authentication legal IP Address |=> return boolean valueV.isfax (");//-- Verify Fax |=> Returns a Boolean valueV.isphone (' 13622667263 ');//--- Verify Phone |=> return boolean valueV.istel (' 021-324234-234 ');//-- Verify Landline |=> return boolean valueV.isurl (' Http://JSLite.io ');//-- Validate URL |=> Returns a Boolean valueV.maxlength (' Jslite ', 12);//- max length |=> returns a Boolean valueV.minlength (' Jslite ', 3);//- min Length |=> returns a Boolean valuev.required (' 23 ');//is required (is empty) |=> returns a Boolean value
Validation in forms

Click on the Submit button to verify and no submit verification difference : No submit verification required at the end Plus

Validator.validate ()

2.Jquery. Validate () Form validation

Validate ([options]):

1.Debug(default: false )

$ (". Selector"). Validate ({  true});

Enables debug mode. If true, the form is not committed and the error is displayed on the console (if the Window.console property exists, will be checked), such as trying to help establish validation about missing methods and other debug message warnings: Try to enable when a form has just been submitted instead of a validation stop commit.

2.Submithandler (default: native form submit )

Ex

Submits the form via Ajax when valid.

$ (". Selector"). Validate ({  function(form) {    $ (form). Ajaxsubmit ();  });

Ex

Use Submithandler to handle something and then use the default commit. Note that the form refers to a DOM element so that validation does not fire again.

3.Invalidhandler

Callback client code when an invalid form is submitted. Invokes the event object as the first argument, validating the second argument.

Ex

An error message appears on the form, indicating how many fields are not valid when the user attempts to submit an invalid form.

$ (". Selector"). Validate ({invalidhandler:function(event, validator) {//' This ' refers to the form    varErrors =Validator.numberofinvalids (); if(Errors) {varmessage = Errors = = 1? ' You missed 1 field. It has been highlighted '        : ' You missed ' + Errors + ' fields. They have been highlighted '; $("Div.error span"). HTML (message); $("Div.error"). Show (); } Else {      $("Div.error"). Hide (); }  }});

4.Ignore (default: ":hidden" )

When validating, simply filter out the elements that need to be ignored.

Ex:ignores all elements with the class "ignore" when validating.

$ ("#myform"). Validate ({  ". Ignore"});

5.rules (default: rules are read from markup (classes, attributes, data) )

Ex

 $ (". Selector" ). Validate ({rules: { //   Name:" Required ",  //  compound rule   email: {required:  true  , email: /span>true   
 $ (". Selector" ). Validate ({rules: {contact: {required:  true   function return  $ (" #contactform_        Email "). Is (": Checked "); }      }    }  }});
$ (". Selector"). Validate ({  rules: {    // at least 15€when bonus material are included     pay_what_you_want: {      true      min: {        //  min needs a Parameter passed to it        param:15,        function(element) {            Return $ ("#bonus-material"). Is (": Checked");}}}  );

6.messages (Default: the default message for the method used )

Ex

 $ (". Selector" ). Validate ({rules: {name:  "Required"  email: {required:  true  , email:  true   "plea Se Specify your name " "We need your email address to cont Act You " "Your email address must is in the format of [Email protec Ted] " 
$ (". Selector"). Validate ({  rules: {    name: {      true,      2    }  },  messages: {    name: {      "We need your email addressto",      minlength: JQuery.validator.format ("at least {0} characters required!" )    }  }});

7.Groups

Use a table layout for the form, placing error messags in the next cell after the input.

$ ("#myform"). Validate ({  groups: {    "fname lname"  },  function(Error , Element) {    if (element.attr ("name") = = "FName" | | element.attr ("name") = = "LName" ) {      error . InsertAfter ("#lastname");     Else {      error.insertafter (element);}}  );

8.ShowErrors

Update the number of invalid elements each time a error is displayed. Delegates to the default implementation for the actual error display.

$ (". Selector"). Validate ({  function(Errormap, errorlist) {    $ ("#summary"). HTML ( "Your form contains" This      . Numberofinvalids ()      + "errors, see details below." );      This . Defaultshowerrors ();  }});

Forms Validation--javascript and jquery editions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.