前端校验和后端校验(JSR303)

一、前端校验

首先前端校验是发生在点击保存按钮或者input输入框失去光标的时候,进行前端校验 a.```xml //新增保存 按钮 $("#stu_save_btn").click(function(){

		//进行前端校验
		if(!validate_add_form()){
			return false;
		}
		//用户名重复校验结果
		if($(this).attr("name-va")=="error"){
			return false;
		}
		
		//保存
		$.ajax({
			url:"${APP_PATH}/emps",
			type:"POST",
			data:$("#add_Modal form").serialize(),
			success:function(result){

				if(result.code==100){
					$('#add_Modal').modal('hide');
					to_page(studentCounts);
				}else{
					if(undefined!=result.extend.errorFields.stuName){
						show_validate_msg("#stu_name_add_input","error",result.extend.errorFields.stuName);
					}
					if(undefined!=result.extend.errorFields.email){
show_validate_msg("#stu_email_add_input","error",result.extend.errorFields.email);
					}
alert(result.extend.errorFields.email);

					alert(result)
				}

			}
		});
	});
b.```xml
//表单添加验证
		function validate_add_form(){
			//校验用户名
			var studentName = $("#stu_name_add_input").val();
			var nameRegx = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
			if(!nameRegx.test(studentName)){
// 				alert("用户名可以是6-16英文和数字组合或2-5位中文~");
				
				show_validate_msg("#stu_name_add_input","error","用户名可以是6-16英文和数字组合或2-5位中文~");
				return false;
			}else{
				show_validate_msg("#stu_name_add_input","success","");
			}
			//校验邮箱
			var studentEmail = $("#stu_email_add_input").val();
			var emailRegx = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
			if(!emailRegx.test(studentEmail)){
				show_validate_msg("#stu_email_add_input","error","邮箱格式不对");
// 				alert("邮箱格式不对");
				return false;
			}else{ 
				show_validate_msg("#stu_email_add_input","success","");
				
			}
			return true;
		}
		function show_validate_msg(ele,status,msg){
			$(ele).parent().removeClass("has-error has-success");
			$(ele).next().text("");
			if(status=="error"){
				$(ele).parent().addClass("has-error");
				$(ele).next().append(msg);
			}
			if(status=="success"){
				$(ele).parent().addClass("has-success");
				$(ele).next().append(msg);
			}
		}

二、以上是对表单的输入框进行输入数据的格式进行校验,一下是在后台对数据名称或者邮件的重复进行校验

//检测用户名可用
		$("#stu_name_add_input").change(function(){
			var StuName = this.value;
			$.ajax({
				url:"${APP_PATH}/checkUser",
				data:"StuName="+StuName,
				type:"POST",
				success:function(result){
					if(result.code==100){
						show_validate_msg("#stu_name_add_input","success","用户名可用");
						$("#stu_save_btn").attr("name-va","success");
					}else if(result.code==200){
						show_validate_msg("#stu_name_add_input","error",result.extend.msg);
						$("#stu_save_btn").attr("name-va","error");
					}
				}
			});
		});

改变之后发送ajax请求获取进行校验 然后后台的Controller中进行进行校验

	@ResponseBody
	@RequestMapping("/checkUser")
	public Msg checkStudent(@RequestParam("StuName") String StuName) {
		String regxName ="(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
		boolean matches = StuName.matches(regxName);
		if(matches==false) {
			return Msg.fail().add("msg","用户名可以是6-16英文和数字组合或2-5位中文~");
		}
		
		boolean b = studentService.checkStu(StuName);
		if(b) {
			return Msg.Success();
		}else {
			return Msg.fail().add("msg","用户名不可用!");
		}
	}

在Service中的代码应该如下所示

public boolean checkStu(String stuName) {
		// TODO Auto-generated method stub
		StudentExample example = new StudentExample();
		Criteria criteria = example.createCriteria();
		criteria.andStuNameEqualTo(stuName);
		
		long l = studentMapper.countByExample(example);
		return l==0;
		
	}

三、后台校验(JSR303校验)

1.需要导入Hibernate validator 中的maven仓库的pom依赖
在这个过程中可能会遇到报错Javax.lang.NoClassDefFoundError , javax el/ELManager错误,
对应的解决方法:将hibernate validator的版本换成6以下的版本,然后同时引入 javax-el-api 3.0的版本就可以解决问题

2.在其中的bean文件中,加入对应的注解

private Integer stuId;
    @Pattern(regexp = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})",
    		message = "用户名可以是6-16英文和数字组合或2-5位中文~")
    private String stuName;

    private String gender;
    @Pattern(regexp = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$",
    		message = "邮箱格式不对~")
    private String email;

    private Integer gId;
    
    private Grade grade;

3.在StudentController中加上校验,以及参数中加入BindingResult result这个参数

/**
	 * 员工保存
	 * @param student
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/emps",method = RequestMethod.POST)
	public Msg saveStudent(@Valid Student student,BindingResult result) {
		
		if(result.hasErrors()) {
			Map map = new HashMap<>();
			List errors = result.getFieldErrors();	
			for (FieldError error: errors) {
				map.put(error.getField(),error.getDefaultMessage());
			}
			return Msg.fail().add("errorFields",map);
		}else {
			studentService.saveStu(student);
			return Msg.Success();
		}
	}

你可能感兴趣的:(java,前端校验,后端JSR303)