1
JQuery Validation Plugin
Calvin Xiao edited this page 2013-11-14 19:16:04 -08:00
This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Official Site : http://jqueryvalidation.org/

Document: http://validation.bassistance.de/documentation/

showcase中的userForm.jsp是最完整的演示。

##良好的客户体验 为什么说客户端验证的体验更好,除了不用真正提交form外就知道错误,它还能:

  • 对于remote的验证,是会在input框失去焦点之后立刻就去做,而其他验证则只在第一次submit之后才会去做。
  • 但一旦发现错误,就会在用户再输入后积极的重新校验,及时消去错误提示信息。
  • 如果出错,光标会智能的focous在出错的input框上.

##基本用法

在input框中的加上标签即可。

<script>
	$(document).ready(function() {
		$("#loginForm").validate();
	});
</script>
<form id="loginForm">
    <input type="text"  name="username" class="required"/>
    <input type="password" name="password" class="required" minlength="3"/>
    <input type="password" name="passwordConfirm" equalTo="#password"/>
</form>

##高级配置 在validate()函数中写Options:

<script>
	$(document).ready(function() {
		$("#inputForm").validate({
			rules: {
				loginName: {
					remote: "${ctx}/account/user/checkLoginName"
				},
				groupList:"required"
			},
			messages: {
				loginName: {
					remote: "User Name Exists"
				},
				passwordConfirm: {
					equalTo: "Input the same password as above"
				}
			},
			errorContainer: "#messageBox",
			errorPlacement: function(error, element) {
				if ( element.is(":checkbox") )
					error.appendTo ( element.parent().next() );
				else
					error.insertAfter( element );
				}
			});
		});
</script>
  • rules: 不方便写在input框里的规则,比如remote规则,会发出Ajax请求校验用户名是否已存在。返回结果如果是"false"文本就是失败。

  • messages: 在默认的出错信息外,定义自己的自定义出错信息。

  • errorContainer: 定义一个总的出错提示信息box,你可以在页面里预先定义一个"输入值有误,请先更正"之类的提示框,先把它hide起来,到了真正有错误发生时,就会显示出来。错误被改正后又会自动隐藏掉。

  • errorPlacement: 默认会在出错的元素后面append一个出错信息框,但像checkbox这种情况,则需要放到一个更高的地方。

##CSS控制 出错时,默认会把input框的class设为error,然后插入一个class为error的,可根据需要进行样式控制。比如springside中就添加了一个红色交叉的图片。

与Twitter bootstrap集成时, errror的会被挤到下一行去,解决方法是换成error element换成元素。

$(document).ready(function() {
		$("#loginForm").validate({
			errorElement: "span"
		});
	});
为了不需要每次都声明一次errorElement, 可以找个地方统一扩展。SpringSide修改了原来的messages_cn.js,添加了下面这句

```js
jQuery.extend(jQuery.validator.defaults, {
    errorElement: "span"
}); 

另外,Bootstrap自带error/warning样式的感觉并不漂亮,因此没有使用,如果要使用的话,可以使用如下语句:

$('#contact-form').validate({
	    highlight: function(label) {
	    	$(label).closest('.control-group').addClass('error');
	    },
	    unhighlight: function(label) {
	    	$(label).closest('.control-group').removeClass('error');
	    }
	  });