JQuery插件:表单数据校验

本文介绍了 jQuery Validation 插件,这是一个广泛使用的表单验证工具,具有易用性和高度可定制的特点。支持本地和远程验证,并能自定义验证规则及错误提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jQuery Validation,最经典的表单数据校验插件(2006年开始,大量网站使用),使用简单、方便自定义和扩展。它由jQuery开发小组的一位成员(Jörn Zaefferer)开发和更新,所以应该比较可靠。


主要特性:
  • 表单提交前对所有数据进行校验,不符合不让提交(validate)
  • 如果表单校验不通过,自动focus到第一个错误的域
  • 自动在控件后面显示错误提示内容(error message)
  • 支持根据name和class进行校验(rule,addClassRules)
  • 支持远程校验(remote)
  • 容易扩展:可以方便地自定义校验规则和提示语(addMethod)
  • 支持自定义提交方式,比如AJAX方式提交(submitHandler)

简单的使用例子:
	<form id="loginForm">
		<div>
			<div>请登录:</div>
			<div>
				<input type="text" maxlength="20" name="userAccount" placeholder="用户名(手机号)" />
			</div>
			<div>
				<input type="password" name="password" placeholder="密码" />
			</div>
			<div>
				<input type="text" id="captcha" placeholder="验证码,大小写都可以"/>
				<span id="captchaChecked" style="display:none;color:green;font-weight:bold">√</span>
			</div>
			<div class="captchaDiv">
				<img class="captcha_img" id="captchaImg" alt="点击刷新验证码">看不清楚?点我!
			</div>
			<div>
				<button type="submit" id="submit">登录</button>
			</div>
		</div>
	</form>
<script>
	var captchaChecked = false;
	
	$(function() {
		refreshCaptcha();
		
		$("#captcha").on("keyup", checkCaptchaInput);
		$(".captchaDiv").on("click", refreshCaptcha);
		//$("#submit").on("click", goLogin);
		
		//表单提交前校验
		$("#loginForm").validate({
			rules: {
				userAccount: {
					required: true,
					mobile: true
				},
				password: "required"
			},
			submitHandler: function(form) {
				goLogin();
  			}
		});
	});
</script>

自定义校验规则和提示语:
比如:
  
jQuery.validator.addMethod("laxEmail", function(value, element) {
// allow any non-whitespace characters as the host part
returnthis.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@(?:\S{1,63})$/.test( value );
}, 'Please enter a valid email address.');
参考:

根据class进行校验:
      
// alias required to cRequired with new message
$.validator.addMethod("cRequired", $.validator.methods.required,
"Customer name required");
// alias minlength, too
$.validator.addMethod("cMinlength", $.validator.methods.minlength,
// leverage parameter replacement for minlength, {0} gets replaced with 2
$.validator.format("Customer name must have at least {0} characters"));
// combine them both, including the parameter for minlength
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });
  
<inputname="customer1"class="customer">
<inputname="customer2"class="customer">
<inputname="customer3"class="customer">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值