`

数据校验:jquery前端验证和hibernate服务端验证

 
阅读更多

 

<%@ 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">
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>"/>
<title>添加/编辑用户</title>
</head>
<body>
	<form action="student.do?save"  id="add_form" method="post" enctype="application/x-www-form-urlencoded">
		<input type="hidden" id="studentId" name="studentId" value="${student.studentId }"/>
		<label>名字:</label><input name="name" id="name" />
		<!--错误信息显示在label里面  -->
		<label></label>
		<label>邮箱:</label><input name="email" id="email"/>
		<input type="submit" value="提交"/>
	</form>

	<script src="<%=basePath%>res/js/jquery.js" type="text/javascript"></script>
	<script src="<%=basePath%>res/js/jquery.validate.js" type="text/javascript"></script>
	<script src="<%=basePath%>res/js/jquery.validate.js" type="text/javascript"></script>
	<script src="<%=basePath%>res/js/messages_cn.js" type="text/javascript"></script>
	<script type="text/javascript">
	 
		 $(document).ready(function() {
		    $("#add_form").validate({
			    rules: {
					"name": {required: true, minlength : 3, maxlength:5},
					"email": {required: true, email : true}
			    }/*
			    自定义报错文字
			    ,
			    messages: {
					"name" : {required: "不能为空", minlength : "大于3", maxlength: "小于5"},
					"email" : {required: "不能为空", email: "请输入正确的email地址"}
			    } */
			    ,
			    errorPlacement: function(error, element) {
				    if ( element.is(":radio") )
				        error.appendTo( element.parent().next().next() );
				    else if ( element.is(":checkbox") )
				        error.appendTo ( element.next() );
				    else {
				        error.appendTo( element.next() );//配置错误信息
				    }
				}
		    });
		}); 
		
	</script>

</body>
</html>

 

新版本:

 /*数据校验,并提交  */
		     $("#edit_form").validate({  
		           submitHandler:function(form){
		               //避免重复提交
						$('#submit_btn').get(0).disabled = true;
		                event.preventDefault();  
		                form.submit();
		            },
		         rules: {  
		             "name": {required: true, maxlength:20} ,
		             "downloadUrl":{required: true, maxlength:128}
		         }
		         ,  
		         messages: {  
		             "name" : {required: "产品名称不能为空", maxlength: "最大不能超过20字符"}, 
		             "downloadUrl" : {required: "下载地址不能为空", maxlength: "最大不能超过128字符"}
		         }  
		         ,  
		         errorPlacement: function(error, element) {  
		             if ( element.is(":radio") )  
		        		 element.after( error ); 
		             else if ( element.is(":checkbox") )  
		        		 element.after( error ); 
		             else {  
		                 element.after( error );//配置错误信息  
		             }  
		         }  
		     });   


在css中如何:
label.error{
	border: 1px dashed red;
	padding: 5px 5px 5px 5px;
	color: red;
	margin: 50px 0 10px 10px;
	background: #FEE;
	font-weight: bold;
}
 

 

问题:对于一个表单中同时存在多个不同名称的input字段,比如通讯录,联系人的电话可能有多个,后面几个电话input是使用动态添加的,

<input name="phone" />

 

<input name="phone"/>//后面这个是动态添加的

 

这时候使用校验,会发现,操作某一个input的时候,校验会绑定到所有的input中name为phone的上面。这个问题如何解决????????

 

需要下载jquery以及他的插件,文章介绍

http://my.oschina.net/wangyongqing/blog/59800

 

 

 

 

服务端数据校验

       下载地址:http://sourceforge.net/projects/hibernate/files/hibernate-validator/4.3.0.Final/hibernate-validator-4.3.0.Final-dist.zip/download

       1、约束设置

      

 

public class Student {
 
    @NotNull(message="学生id不能为空", groups = EditChecks.class)
    private Integer studentId;
    @NotNull(message="姓名不能为空")
    @Min(value=4, message="姓名长度不能小于4", groups = EditChecks.class)
    private String name;
   
    private Teacher teacher;
 

 

解释:

@NotNull  @Min就是hiberante validate默认的一些约束给我们使用(2.4.1节列出了一些我们可以使用的),括号里面meesage定义了不符合约束时候返回的信息,groups是分组

Groups:这个很重要,比如studentId在新增学生的时候,他必然为空,此时他必定为null,但是在编辑的时候他就必须有值,所以hibernate validate就提供了分组的概念,对于有定义某一组,他就使用那组进行约束,如果没有就使用默认组。具体请查看官方文档2.3节校验组。

 

2、代码中如何处理:

工具类:validateUtils

 

public class ValidateUtils<T, E> {
   
    public ValidateUtils() {}
   
    private Validator getValidator() {
       ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
       Validator validator = factory.getValidator();
       return validator;
    }
   
//这里有使用分组
    public String getViolationMsgs(T clazz, Class<E> check) {
       Validator validator = this.getValidator();
       String msg = "";
       Set<ConstraintViolation<T>> constraintViolations = null;
       constraintViolations = validator.validate(clazz, check);
//判断是否有约束错误
       if(!CollectionUtils.isEmpty(constraintViolations)) {
           msg = constraintViolations.iterator().next().getMessage();
       }
       return msg;
    }
   
//不使用分组
    public String getViolationMsgs(T clazz) {
       Validator validator = this.getValidator();
       String msg = "";
       Set<ConstraintViolation<T>> constraintViolations = null;
       constraintViolations = validator.validate(clazz);
       if(!CollectionUtils.isEmpty(constraintViolations)) {
           msg = constraintViolations.iterator().next().getMessage();
       }
       return msg;
    }
}
 

逻辑层类spring mvc的某一个方法

 

private static ValidateUtils validateUtils = new ValidateUtils();
@RequestMapping(params="save",method={RequestMethod.POST})
    public String save(Student student, WebRequest request) {
      
       if(student.getStudentId()==null) {
           //String str = validateUtils.getViolationMsgs(student);
            //对于保存就使用默认的组,或者使用上面那个也行,下面获取返回的约束message
           String str = validateUtils.getViolationMsgs(student, Default.class);
           System.out.println(str);
           int id = (Integer) this.studentService.save(student);
           this.log.debug(id);
       }
       else {
           String str = validateUtils.getViolationMsgs(student, EditChecks.class);
           System.out.println(str);
           this.studentService.update(student);
       }
      
       List<Student> list = this.studentService.findAll(Student.class);
       request.setAttribute("list", list, 0);
       return "redirect:student.do?list";
    }
 

 

官方文档中有提供了一些:

1、自定义的约束(判断大小写啊等)

2、启动validate的三种方法。

3xml配置,等

总结:1、官方提供的基本够用;2、既然我们要使用annotation,就不用xml配置了。3、其他的用到的时候再查,个人感觉上面这些已经够了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics