使用JQuery的validate插件做客户端验证非常方便,下面做一个使用validate插件验证用户注册信息的例子。
本实例使用的是1.5版本。
示例是在SSH下做的,代码如下:
registe.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>注册页面</title> <mce:script type="text/javascript" src="js/jquery.1.4.2.js" mce_src="js/jquery.1.4.2.js"></mce:script> <mce:script type="text/javascript" src="js/validate/jquery.validate.js" mce_src="js/validate/jquery.validate.js"></mce:script> <link href="js/validate/jquery.validate.css" mce_href="js/validate/jquery.validate.css" type="text/css" rel="stylesheet"/> <mce:script type="text/javascript"><!-- //扩展validator的校验方法 $.validator.addMethod("onlyLetterAndDigit",function(value, element, params){ var regex=new RegExp('^[0-9a-zA-Z]+$'); return regex.test(value); },"只能输入字母或数字"); $(function(){ $("#registe").validate({ //定义验证规则,其中属性名为表单的name属性 rules:{ username:{ required:true, onlyLetterAndDigit:true,//使用自定义方法限制只能输入字母或数字 rangelength:[4,20], remote:"registe!validName.action"//使用AJAX异步校验 }, password:{ required:true, rangelength:[4,20] }, chkpassword:{ required:true, equalTo:"#password" }, email:{ required:true, email:true }, vercode:"required" }, messages:{ username:{ required:"请输入用户名", rangelength:"用户名长度必须在4~20位之间", remote:$.format("用户名{0}已存在,请重新输入!") }, password:{ required:"请输入密码", rangelength:"密码长度必须在4~20位之间" }, chkpassword:{ required:"请再次输入密码", equalTo:"密码输入不一致,请重新输入" }, email:{ required:"请输入电子邮件", email:"请输入合法的电子邮件" }, vercode:{ required:"请输入验证码" } } }); }); //刷新验证码 function refresh() { $("#authImg").src="authImg?now="+new Date(); } // --></mce:script> </head> <body> <form action="registe.action" method="post" id="registe"> <table> <caption><h2 id="用户注册">用户注册</h2></caption> <tr> <td>用 户 名:</td><td><input type="text" name="username" id="username"/></td> </tr> <tr> <td>密 码:</td><td><input type="text" name="password" id="password"/> </td> </tr> <tr> <td>确认密码:</td><td><input type="text" name="chkpassword"/></td> </tr> <tr> <td>Email:</td><td><input type="text" name="email"/></td> </tr> <tr> <td>验证码:</td><td valign="bottom"><input type="text" name="vercode" size="10"/> <img src="/static/imghwm/default1.png" data-src="authImg" class="lazy" alt="" mce_ id="authImg" align="absmiddle"><a href="#" mce_href="#" onclick="refresh()"><span style="max-width:90%" mce_style="font-size:12px">刷新验证码</span></a></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"/><input type="reset" value="重填"/></td> </tr> </table> </form> </body> </html>
后台RegisteAction.java的主要方法
public String execute() throws Exception { Map session = ActionContext.getContext().getSession(); String ver2 = (String) session.get("rand"); session.put("rand", null); //判断验证码是否正确 if (vercode.equals(ver2)) { if (userManager.validName(username)) { if (userManager.addUser(username, password, email) > 0) return SUCCESS; else addActionError("注册失败,请重试!"); } else { addActionError("该用户名已存在,请重新输入!"); } } else { addActionError("验证码不匹配,请重新输入"); } return INPUT; } //验证用户名是否可用 public String validName() throws Exception { System.out.println(username); boolean flag = userManager.validName(username); HttpServletResponse response = ServletActionContext.getResponse(); response.setDateHeader("Expires", 0); response.addHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/plain;charset=UTF-8"); if (flag) response.getWriter().write("true"); else response.getWriter().write("false"); response.getWriter().flush(); // 因为直接输出内容而不经过jsp,因此返回null. return null; }
效果图如下:
注意:使用remote异步验证用户名的方法应该通过response.getWriter().write("true")来输出,而不能像普通方法一样返回字符串。
关于插件更详细的介绍可以查看“jQuery validate验证插件使用详解”。
另外,jQuery也支持动态给控件添加校验,例如:
但要注意:如果对集合中的元素动态添加校验需要循环对每个元素添加,这是因为jQuery隐式实现了集合操作,但validate插件没有。例如:
$(".quantity").each(function(){ $(this).rules("add",{digits:true,required:true}); });
以上就是本文的全部内容,希望对大家的学习有所帮助。

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

SublimeText3 English version
Recommended: Win version, supports code prompts!
