JQuery validate插件验证用户注册信息_jquery
使用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/imghw/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}); });
以上就是本文的全部内容,希望对大家的学习有所帮助。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute
