search
HomeWeb Front-endJS TutorialSummary of submission methods of validate and form plug-ins in jquery_javascript skills

Overview: This article mainly discusses jquery.validate combined with jquery.form to implement form verification and submission solutions.

Method 1: Through the submitHandler option of jquery.validate, that is, the callback function is executed when the form passes verification. Submit the form through jquery.form in this callback function;

Method 2: Through beforeSubmit of jquery.form, which is a callback function executed before submitting the form. If this function returns true, the form is submitted. If it returns false, the form submission is terminated. According to the valid() method of the jquery.validate plug-in, the form can be verified when submitting the form through jquery.form.

Method 3: Validate the form through jquery.validate. The advantage of this method is that you have more control over form validation

Examples: The above three methods are explained below through three examples

Load CSS style file

Copy code The code is as follows:

CSS style file content

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;
}

Load javascript file

<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提交的三种方式</legend>
  <p>
   <label for='cusername'>姓名</label><em>*</em>
   <input id='cusername' name='username' size='25' />
  </p>
  <p>
   <label for='cemail'>电子邮件</label><em>*</em>
   <input id='cemail' name='email' size='25' />
  </p>
  <p>
   <input class='submit' type='submit' value='提交'>
  </p>
 </fieldset>
</form>
</body>

jquery.validate+jquery.form submits the javascript content of method 1

<script language="javascript">
function showResponse(responseText,statusText) {
 if(statusText=='success'){
  $("#result").html(responseText);
 }
}

$(document).ready(function(){
 $('#commentForm').validate({
  focusCleanup:true,focusInvalid:false,
  errorClass: "unchecked",
  validClass: "checked",
  errorElement: "span",
  submitHandler:function(form){
   $(form).ajaxSubmit({
    type:"post",
    url:"test_save.php&#63;time="+ (new Date()).getTime(),
    //beforeSubmit: showRequest,
    success: 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 submits the javascript content of method 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_save.php&#63;time="+ (new Date()).getTime(),
   beforeSubmit:showRequest,
   success:showResponse
  });
  return false; //此处必须返回false,阻止常规的form提交
 });

 $('#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 submits the javascript content of method 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("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 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&#63;time="+ (new Date()).getTime(),
   beforeSubmit:showRequest,
   success:showResponse
  });
  return false; //此处必须返回false,阻止常规的form提交
 });
});
</script>

DEMO source code: Download

Some questions

1. In fact, this problem was discovered when I wrote this article last night. When I used in the HTML file header, there seemed to be some problems with the style of the input box and error message. However, today I discovered that the problem is not that simple. When using , for the "name" input box - it only needs to reach three characters to be considered passed the verification - after entering the first character, the second character characters, the error display is normal. When the third character is entered, the error display disappears, and a "comma" picture indicating that the verification is passed is displayed. So far, everything seems to be working fine, but if you continue to enter characters, such as the fourth character, the fifth character... the problem arises. As shown below:

No such problem when using instead of using , everything works fine. However, the question now is, why does adding cause such a problem? Moreover, as a front-end, adding is necessary.

This problem is quite complicated to deal with. Here is a list of the process. And give a solution at the end

First of all, it’s because I was checking the error message yesterday and paid attention to the code that inserted the error message. I added a sentence 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 something like the picture below

Enter three characters. After successful verification, you will get the following picture:

Continue to enter more characters and get the result as shown below

This illustrates the following issues:

1. Regardless of whether the verification fails or succeeds, errorPlacement:function(...)

will be called

2. s.remove() does not work.

Since I used instead of when writing this article, the pop-up content is htmlFor="cusername" instead of for="cusername", as shown in the following figure:

Therefore, the above code is written as follows

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

However, under , cannot be found based on htmlFor, so htmlFor should be changed to for here, that is,

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());
},

问题似乎解决了。但上面提到,不管验证成功或失败,都会调用errorPlacement:function(...),那可以在这里判断有没有错误,如果有错误,则显示。防止已经验证成功的情况下仍会调用。这样就不会寻找span的for属性值是否为当前控件的name名称了(例子中是for="cusername")。改进的代码如下:

errorPlacement:function(error,element){
 if(error.html()!=''){
  error.appendTo(element.parent());
 }
},

虽然解决问题,但是在chrome、firefox下仍有问题。了解这个问题的现象,可以用firefox或chrome测试一下——焦点离开输入框后,无法验证,只有点击“提交”按钮后才可以验证——这个问题的解决方案目前还没有深入下去。但是有解决的办法是,将上面的jquery1.6.2换成jquery1.3.2或jquery1.4(其它的jquery版本未测试,可能是低于jquery1.6.2的版本都可以)即可解决这个问题。

建议:

1、使用jquery1.3.2版本,这样可以节省很多时间来解决兼容方面的问题。

更多:

本例子中的jquery.validate,解决了remote远程验证只返回true or false的局限。可以返回代码及出错的提示信息,更好的人性化需求。使用方法就在这介绍一下

增加以下函数

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" &#63; true : false;
    return result;
   }
  }
 };
 return remote;
}

$(document).ready(function(){
 var dataInfo ={email:function(){return $("#cemail").val();}};
 var remoteInfo = GetRemoteInfo('check-email.php&#63;time='+(new Date()).getTime(),dataInfo);
 $('#commentForm').validate({
  rules:{
   username:{
    required:true,
    minlength:3
   },
   email:{
    required:true,
    remote:remoteInfo
   }
  }
 });
 ....
});

check-email.php返回的内容为xml格式,格式如下

<&#63;php
header("Content-Type:text/xml");
echo '<&#63;'.'xml version="1.0" encoding="utf-8"'.' &#63;>';
&#63;>
<AjaxClass>
<Msg>用户名格式不正确,用户名必须包含testa,请重新输入!</Msg>
<Result>0</Result>
</AjaxClass>

result值为0,返回的是false,表示验证失败;result值为1,返回的是true,表示验证成功

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools