본문 바로가기

개발(합니다)/Java&Spring

Spring 유효성 검사(interface)

반응형

맴버 정보 수정하는 과정에서 유효성 검사를 정리합니다.





1. MemberValid.java

package com.otrodevym.mfaw.member.vo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.otrodevym.mfaw.common.MessageUtils;

public class MemberValid implements Validator{
    /*
     *
     * 1) 숫자만 : ^[0-9]*$
     *
     * 2) 영문자만 : ^[a-zA-Z]*$
     *
     * 3) 한글만 : ^[가-힣]*$
     *
     * 4) 영어 & 숫자만 : ^[a-zA-Z0-9]*$
     *
     * 5) E-Mail : ^[a-zA-Z0-9]+@[a-zA-Z0-9]+$
     *
     * 6) 휴대폰 : ^01(?:0|1|[6-9]) - (?:\d{3}|\d{4}) - \d{4}$
     *
     * 7) 일반전화 : ^\d{2,3} - \d{3,4} - \d{4}$
     *
     * 8) 주민등록번호 : \d{6} \- [1-4]\d{6}
     *
     * 9) IP 주소 : ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3})
     *
     *
     *
     */
    @Override
    public boolean supports(Class<?> clazz) {
        return MemberVO.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MemberVO memberVo = (MemberVO) target;
        
        String user_id = "^[a-z | A-Z]{3,6}[0-9]{3,6}$";
        String password = "^.*(?=.{6,20})(?=.*[0-9])(?=.*[a-zA-Z]).*$";
        String email =
"^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|
(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        String phone = "^(01[1|6|7|8|9|0])-(\\d{3,4})-(\\d{4})$";
        String name = "^[가-힣]{2,6}$";
        String birth_day = "^[0-9]{4}-[0-9]{2}-[0-9]{2}";
        String solar_birth_yn = "^[0-1]{1}$";
        String address = "^[가-힣]+[가-힣\\s]*$";
        Matcher m = null;

        // 2019.01.24 otrodevym : 아이디 유효성 검사
        m = Pattern.compile(user_id).matcher(memberVo.getUser_id());
        if (m.find()) {

        } else {
            errors.rejectValue("user_id", MessageUtils.getMessage("Pattern.memberVo.user_id"));
        }

        m = Pattern.compile(password).matcher(memberVo.getPassword());
        if (m.find()) {

        } else {
            errors.rejectValue("password", MessageUtils.getMessage("Pattern.memberVo.password"));
        }
        m = Pattern.compile(email).matcher(memberVo.getEmail());
        if (m.find()) {

        } else {
            errors.rejectValue("email",MessageUtils.getMessage("Email.memberVo.email"));
        }

        m = Pattern.compile(phone).matcher(memberVo.getPhone());
        if (m.find()) {

        } else {
            errors.rejectValue("phone", MessageUtils.getMessage("Pattern.memberVo.phone"));
        }

        m = Pattern.compile(name).matcher(memberVo.getName());
        if (m.find()) {

        } else {
            errors.rejectValue("name", MessageUtils.getMessage("Pattern.memberVo.name"));
        }

        m = Pattern.compile(birth_day).matcher(memberVo.getBirth_day());
        if (m.find()) {

        } else {
            errors.rejectValue("birth_day", MessageUtils.getMessage("Pattern.memberVo.birth_day"));
        }
        System.err.println(memberVo.getSolar_birth_yn());
        m = Pattern.compile(solar_birth_yn).matcher(memberVo.getSolar_birth_yn());
        if (m.find()) {

        } else {
            errors.rejectValue("solar_birth_yn",
MessageUtils.getMessage("Pattern.memberVo.solar_birth_yn"));
        }

        m = Pattern.compile(address).matcher(memberVo.getAddress());
        if (m.find()) {

        } else {
            errors.rejectValue("address", MessageUtils.getMessage("Pattern.memberVo.address"));
        }  
    }
}



2. Contoller

    @ResponseBody
    @PutMapping(value = "")
    public String memberUpdate(Model model, @RequestBody MemberVO memberVo,
            BindingResult bindingResult) throws JsonProcessingException {
        logger.info("-------------PUT member -----");
        
        // 2019.01.24 otrodevym : 유효성 검사
        MemberValid memberValid = new MemberValid();
        memberValid.validate(memberVo, bindingResult);
        
        
        ObjectMapper mapper = new ObjectMapper();
        if (bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
            HashMap<String, Object> map = new HashMap<>();
            map.put("errors", errors);
            map.put("check", "fail");
            return mapper.writeValueAsString(map);
        }
        memberService.memberUpdateInfo(memberVo);

        return mapper.writeValueAsString("success");
    }


MemberValid를 생성하고 validate를 호출하여 유효성 검사를 합니다.

유효성 검사에서 에러가 발생하면 bindingResult에 저장되고 에러를 View단으로 전달합니다.

3. 실행 결과




반응형