How validate and form Plug-ins are submitted in jquery summary _javascript tips

Source: Internet
Author: User

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

Mode one: It is through the jquery.validate submithandler option, that is, the callback function is executed when the form is validated. Submits the form through Jquery.form in this callback function;

Mode two: It is through the Jquery.form Beforesubmit, the callback function that executes before submitting the form, which, if returned true, submits the form and, if false, terminates the submission of the form. Depending on the valid () method of the Jquery.validate plug-in, the form can be validated when the form is submitted by Jquery.form.

Mode three: Is the Validate method that verifies the form by Jquery.validate. The advantage of this approach is that control of form validation is more free

Example: The following three examples illustrate the above three ways respectively

Load CSS style files

Copy Code code as follows:
<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 submitted in three ways </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= '
   submission ' value= ' submitted ' >
  </p>
 </fieldset>
</form>
</body>

Jquery.validate+jquery.form the JavaScript content of 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 ({Typ E: "Post", url: "Test_save.php?time=" + (new Date ()). GetTime (),//beforesubmit:showrequest, success:showrespons
  e}); 
   }, 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 the JavaScript content of 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 '). Submit (function () {$ (this). Ajaxsubmit ({type: "post", url: "Test_sa
  Ve.php?time= "+ (new Date ()). GetTime (), Beforesubmit:showrequest, success:showresponse}); return false;

 You must return false here to block the regular form submission});
  $ (' #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 the JavaScript content of 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 (). Find ("s
   Pan[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 Showresponse (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;
You must return false here to block 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 <! in the HTML file header When DOCTYPE html>, there seems to be some problem with the style of the input box and the error message. But today it's not so easy to find the problem, using <! When DOCTYPE html>, for the "name" of this input box---------------------only three characters are considered authenticated--when you enter the first character, the second character, the error appears normal, when you enter the third character, the error display disappears and a "comma" So far, everything seems to be normal, but if you continue to enter characters, such as entering the fourth character, the fifth character ... The problem arises. As shown in the following illustration:

Do not use <! DOCTYPE Html>, while using

This problem to deal with the more tangled, here list the process of processing. And at the end give a solution

First, because yesterday you were looking at the error message, look at the code that inserted the error message. I added a phrase to 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 the following figure

Enter three characters, and after the validation is successful, it is shown in the following illustration:

Continue to enter more characters, as shown in the following figure

This illustrates the following issues:

1, regardless of authentication failure or success, will invoke Errorplacement:function (...)

2, S.remove () did not work.

Because of the use of

So, the code above is written in the following way

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

However, in <! DOCTYPE html>, cannot find <span generated= "true" htmlfor= "Cusername" ></span> by htmlfor, so you should change htmlfor to for , namely

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, it is mentioned above that the Errorplacement:function (...) is invoked regardless of the success or failure of the validation, which can be used to determine if there is an error or if there is an error. This is still invoked to prevent successful validation. This will not look for the span's for property value as the name of the current control (in the case of for= "Cusername"). 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 with Chrome and Firefox. To understand the phenomenon of this problem, you can use Firefox or Chrome test-focus left the input box, can not be verified, only click the "Submit" button to verify the problem-the solution is not in depth. The solution, however, is to replace the above jquery1.6.2 with jquery1.3.2 or jquery1.4 (other jquery versions are not tested and may be less than the jquery1.6.2 version) to solve the 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 returns TRUE or False only. Can return the code and error information, better human needs. The way to use this is 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 and is formatted as follows

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

A result value of 0 returns false, indicating that the validation failed; The result value is 1, and returns True, indicating successful validation

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.