后台数据校验-BeanFrom

package com.ldf.domain;

import java.text.ParseException;

public class UserFrom {
	
	//从表单获取的数据
	private String username; 
	private String password;
	private String repassword;
	private String email;
	private String birthday;
	
	//创建一个存储验证信息的msgMap
	Map<String, String> msg = new HashMap<String, String>();

	public boolean validata(){
		//验证用户名
		if ("".equals(username)) {
			msg.put("username", "用户名不能为空!!");
		}else if(!username.matches("^[a-zA-Z][a-zA-Z0-9]{2,15}$")){
			msg.put("username", "用户名长度为3~15之间,必须以字母开头");
		}else if (new UserServiceImpl().findUserByName(username)) {//创建一个user服务
			msg.put("username", "用户名已经存在!请重新输入!");
		}
		
		//验证密码
		if ("".equals(password)) {
			msg.put("password", "密码不能为空!!");
		}else if(!password.matches("^[a-zA-Z0-9]{4,10}$")){
			msg.put("password", "密码不能含有非法字符,长度在4-10之间");
		}
		
		//验证确认密码
		if ("".equals(repassword)) {
			msg.put("repassword", "确认密码不能为空!!");
		}else if (!repassword.equals(password)) {
			msg.put("repassword", "两次密码不一致");
		}
		
		//验证邮箱
		if ("".equals(email)) {
			msg.put("email", "邮箱不能为空!!");
		}else if(!email.matches("^\\w+@\\w+(\\.[a-zA-Z]{2,3}){1,2}$")){
			msg.put("email", "邮箱格式不正确,例如[email protected]");
		}
		//验证生日
		if ("".equals(birthday)) {
			msg.put("birthday", "生日不能为空!!");
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				sdf.parse(birthday);
			} catch (ParseException e) {
				msg.put("birthday", "生日格式不对,正确为yyyy-MM-dd");
			}
		}
		
		return msg.isEmpty();
	}
	//省略getter和setter方法
}

  1.验证信息包括,表单各项信息是否为空,两次密码是否一致,各项信息格式是否正确,用户名是否存在,验证码是否正确(待更新)

  2.从表单获取的数据,字段定义要与表单中的数据字段定义一致,从表单获得的数据格式都为String,因此BeanFrom中字段定义的时候,数据类型全部为String.

//从表单获取的数据
private String username; 
private String password;
private String repassword;
private String email;
private String birthday;

  3.Map集合是用来存储验证的错误信息.错误信息的key要与字段定义一致.判断错误的顺序一般为  空->格式->特有判断.

  4.正则表达式的知识

  5.时间判断上通过SimpleDateFormat类,进行格式判断,如果格式正确,birthday字符串将转换为Date数据,说明符合格式;如果格式不正确,在转换过程中就会产生ParseException,将错误信息,封装到msg中即可.

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  try {
	sdf.parse(birthday);
  } catch (ParseException e) {
	msg.put("birthday", "生日格式不对,正确为yyyy-MM-dd");
  }

  6.如果msg为空,就说明没有任何错误信息被添加,也就说明验证成功,没有产生任何的错误,验证通过;反之,验证失败,将错误信息封装到msg中,通过一定的方式传到页面中.

猜你喜欢

转载自www.cnblogs.com/liu1275271818/p/10113018.html
今日推荐