Three ways to submit Jquery.validate+jquery.form

Source: Internet
Author: User

Overview : This article mainly discusses jquery.validate combined with Jquery.form to implement the validation and submission of forms.

Mode one: The Submithandler option is passed through the jquery.validate, that is, when the form is validated, the callback function is executed. Submit the form through Jquery.form in this callback function;

Way two: is through the Jquery.form Beforesubmit, that is, the execution of the form before the callback function, if this function returns True, the form is submitted, if False, the submission form is terminated. Depending on the valid () method of the Jquery.validate plug-in, the form can be validated by Jquery.form when the form is submitted.

Way three: Is the Validate method that verifies the form through Jquery.validate. The benefit of this approach is that the control of forms validation is more free

Example : The following three examples are described above in three ways

Loading CSS style files

<link rel= "stylesheet" type= "text/css" media= "screen" href= "Style.css"/>

CSS style file contents

input{  height:25px;  line-height:25px;  padding-left:4px;} span.checked{  padding:0px 5px 0px 25px;  margin-left:10px;  margin-top:0px;  margin-bottom:3px;  height:25px;  line-height:25px;  font-size:12px;  White-space:nowrap;  Text-align:left;  Color: #E6594E;  Background:url ("Images/acion2.png") no-repeat 3px; /* #FCEAE8 */}span.unchecked{  padding:0px 5px 0px 25px;  margin-left:10px;  margin-top:0px;  margin-bottom:3px;  height:23px;  line-height:23px;  font-size:12px;  border:1px solid #E6594E;  White-space:nowrap;  Text-align:left;  Color: #E6594E;  Background: #FCEAE8 URL ("images/acion.png") No-repeat 3px;}

Loading JavaScript files

<script language= "JavaScript" type= "Text/javascript" src= "Js/jquery1.6.2.js" ></script><script Language= "JavaScript" type= "Text/javascript" src= "js/jquery.form.js" ></script><script language= " JavaScript "type=" Text/javascript "src=" js/jquery.validate.js "></script><script language=" JavaScript " Type= "Text/javascript" src= "Js/localization/messages_tw.js" ></script>

HTML content

<body><span id= "Result" ></span><form id= ' commentform ' >  <fieldset>  < Legend>jquery.validate+jquery.form three ways to submit </legend>    <p>      <label for= ' cusername ' > name </label><em>*</em>      <input id= ' cusername ' name= ' username ' size= ' "/>    </p>    <p>      <label for= ' cemail ' > email </label><em>*</em>      <input id= ' Cemail ' Name= ' email ' size= '/>    </p>    <p> <input class= ' submit ' type= ' submit '      value= ' submission ' >    </p>  </fieldset></form></body>

Jquery.validate+jquery.form JavaScript content for submission mode 1

<script language= "JavaScript" >function Showresponse (Responsetext,statustext) {if (statustext== ' success ') {$ ("  #result "). HTML (responsetext); }}$ (document). Ready (function () {$ (' #commentForm '). Validate ({focuscleanup:true,focusinvalid:false, errorclass: "UN        Checked ", Validclass:" Checked ", Errorelement:" Span ", submithandler:function (form) {$ (form). Ajaxsubmit ({ Type: "Post", url: "Test_save.php?time=" + (new Date ()). GetTime (),//beforesubmit:showrequest, suc    Cess:showresponse}); }, Errorplacement:function (error,element) {var s=element.parent (). Find ("span[htmlfor=" + element.attr ("id") + "']      ");      if (s!=null) {s.remove ();    } error.appendto (Element.parent ());      }, success:function (label) {//label.addclass ("valid"). Text ("ok!")    Label.removeclass ("Unchecked"). AddClass ("checked"); }, rules:{Username:{required:true,minlength:3}, email:{required:true}});}); </script>

Jquery.validate+jquery.form JavaScript content for submission Mode 2

<script language= "JavaScript" >function Showresponse (Responsetext,statustext) {if (statustext== ' success ') {$ ("  #result "). HTML (responsetext); }}function Showrequest (formdata,jqform,options) {return $ ("#commentForm"). valid (); $ (document). Ready (function () {$ (' #commentForm '). The Submit (function () {$ (this). Ajaxsubmit ({type: "post", url: "Te    St_save.php?time= "+ (new Date ()). GetTime (), Beforesubmit:showrequest, success:showresponse}); return false;  You must return false here to prevent regular form submissions}); $ (' #commentForm '). Validate ({focuscleanup:true,focusinvalid:false, Errorclass: "Unchecked", Validclass: "Checked" , errorelement: "Span", Errorplacement:function (error,element) {var s=element.parent (). Find ("span[htmlfor=" +      ELEMENT.ATTR ("id") + "']");      if (s!=null) {s.remove ();    } error.appendto (Element.parent ());      }, success:function (label) {//label.addclass ("valid"). Text ("ok!") Label.removeclass ("Unchecked"). AddClass ("checked"); }, rules:{Username:{required:true,minlength:3}, email:{required:true}}); </script>

Jquery.validate+jquery.form JavaScript content for submission mode 3

<script language= "JavaScript" > var options={focuscleanup:true,focusinvalid:false, Errorclass: "Unchecked", Validclass: "Checked", Errorelement: "Span", Errorplacement:function (error,element) {var s=element.parent (). f      IND ("span[htmlfor=" + element.attr ("id") + "']");      if (s!=null) {s.remove ();    } error.appendto (Element.parent ());      }, success:function (label) {//label.addclass ("valid"). Text ("ok!")    Label.removeclass ("Unchecked"). AddClass ("checked"); }, rules:{Username:{required:true,minlength:3}, email:{required:true}}};function Showres  Ponse (Responsetext,statustext) {if (statustext== ' success ') {$ ("#result"). HTML (responsetext); }}function Showrequest (formdata,jqform,options) {return $ ("#commentForm"). valid ();  $ (document). Ready (function () {validator=$ (' #commentForm '). Validate (options);  $ ("#reset"). Click (function () {validator.resetform ();  }); $ ("button"). Click (function () {validAtor.form ();  }); $ (' #commentForm '). Submit (function () {$ (this). Ajaxsubmit ({type: "post", url: "Test_save.php?time=" + (new Date ()    ). GetTime (), Beforesubmit:showrequest, success:showresponse}); return false; This must return false to prevent the regular form submission}); </script>

Demo Source: Download

Some questions

1, in fact, this problem was written last night when the article was found that I used the HTML file header <! When DOCTYPE html>, the style of the input box and the error message seems to be problematic. But today it's not that simple to use <!. DOCTYPE html>, for the "name" of this input box--only three characters to be considered to be verified--when the first character, the second character, the error display is normal, enter the third character, the error display disappears, and displays a "comma" picture of the validation passed. So far, everything seems to be normal, but if you continue to enter characters, such as entering a fourth character, the fifth character ... The problem arises. As shown in the following:

Do not use <! DOCTYPE Html> While using

This problem is handled more tangled, here is a list of processing process. And in the end give a solution

First of all, because yesterday, when you look at the error message, follow the code to insert the error message. I added a sentence in errorplacement: alert (Element.parent (). HTML ());

Errorplacement:function (error,element) {  alert (element.parent (). HTML ());  var s=element.parent (). Find ("span[htmlfor=" + element.attr ("id") + "']");  if (s!=null) {    s.remove ();  }  Error.appendto (Element.parent ());},

When you enter the first character, you get as shown

Enter three characters, and after validation succeeds, get as shown:

Continue to enter more characters to get as shown

This illustrates the following issues:

1, regardless of validation failure or success, will call Errorplacement:function (...)

2, S.remove () does not work.

Since I was writing this article, I used

Therefore, the above code is written as follows

  var s=element.parent (). Find ("span[htmlfor= '" + element.attr ("id") + "']");  if (s!=null) {    s.remove ();  }

However in <! DOCTYPE html>, cannot find <span class= "checked" generated= "true" htmlfor= "Cusername" ></span> according to Htmlfor; So here we should change the htmlfor to for, that

Errorplacement:function (error,element) {  alert (element.parent (). HTML ());  var s=element.parent (). Find ("span[for = '" + element.attr ("id") + "']");  if (s!=null) {    s.remove ();  }  Error.appendto (Element.parent ());},

The problem seems to have been solved. However, as mentioned above, regardless of validation success or failure, will call Errorplacement:function (...), that can be judged here there is no error, if there is an error, it is displayed. It is still called if the validation has been successful. This will not look for the span's for property value as the name of the current control (for= "Cusername" in the example). The improved code is as follows:

Errorplacement:function (error,element) {  if (error.html () = ") {    error.appendto (element.parent ());}  } ,

Although the problem is solved, there are still problems in Chrome and Firefox. To understand the problem, you can test it with Firefox or Chrome-the focus leaves the input box and cannot be verified-the solution to this problem is not yet available for verification until you click on the "Submit" button. However, the solution is to replace the above jquery1.6.2 with jquery1.3.2 or jquery1.4 (other jquery versions are not tested and may be below the jquery1.6.2 version) to solve this problem.

Suggestions:

1, use jquery1.3.2 version, this can save a lot of time to solve the compatibility problem.

More:

The jquery.validate in this example solves the limitation that Remote authentication only returns TRUE or false. can return code and error messages, better user-friendly needs. How to use it here to introduce

Add the following function

function Getremoteinfo (posturl,data) {  var remote = {    type: "POST",    Async:false,    Url:posturl,    DataType: "xml",    Data:data,    datafilter:function (dataxml) {      var result = new Object ();      Result. result = JQuery (DataXML). Find ("result"). Text ();      Result. msg = JQuery (dataxml). Find ("MSG"). text ();      Alert (result. Result);      if (result. result = = "-1") {        result. Result = false;        return result;      } else{        result. result = result. Result = = "1"? True:false;        return result;}}  ;  return remote;}
$ (document). Ready (function () {  var datainfo ={email:function () {return $ ("#cemail"). val ();};  var remoteinfo = getremoteinfo (' check-email.php?time= ' + (new Date ()). GetTime (), datainfo);  $ (' #commentForm '). Validate ({    rules:{      username:{        required:true,        minlength:3      },      email:{        Required:true,        remote:remoteinfo      }}}  );  ....});

The content returned by check-email.php is in XML format, in the following format

<?phpheader ("Content-type:text/xml"); Echo ' <? '. ' XML version= "1.0" encoding= "Utf-8" '. '?> ';? ><AjaxClass><Msg> username format is incorrect, username must contain Testa, please re-enter!</msg><result>0</result></ Ajaxclass>

A result value of 0, which returns FALSE, indicates that the validation failed, the result value is 1, and the return is true, indicating that the validation was successful

Three ways to submit Jquery.validate+jquery.form

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.