Validation

์ฃผ๋กœ ์‚ฌ์šฉ์ž ๋˜๋Š” ์„œ๋ฒ„์˜ ์š”์ฒญ (http request) ๋‚ด์šฉ์„ ํ™•์ธํ•˜๋Š” ๋‹จ๊ณ„

Validation์˜ ์ข…๋ฅ˜

๋ฐ์ดํ„ฐ ๊ฒ€์ฆ

  • ํ•„์ˆ˜ ๋ฐ์ดํ„ฐ์˜ ์กด์žฌ ์œ ๋ฌด

  • ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋‚˜ ๋ฐ์ดํ„ฐ ๊ฐ’์˜ ๋ฒ”์œ„

  • email, ์‹ ์šฉ์นด๋“œ ๋ฒˆํ˜ธ ๋“ฑ ํŠน์ • ํ˜•์‹์— ๋งž์ถ˜ ๋ฐ์ดํ„ฐ

๋น„์ฆˆ๋‹ˆ์Šค ๊ฒ€์ฆ

  • ์„œ๋น„์Šค ์ •์ฑ…์— ๋”ฐ๋ผ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฒ€์ฆ

  • ์˜ˆ) ๋ฐฐ๋‹ฌ์•ฑ์ธ ๊ฒฝ์šฐ ๋ฐฐ๋‹ฌ ์š”์ฒญ์„ ํ•  ๋•Œ ํ•ด๋‹น ์ฃผ๋ฌธ ๊ฑด์ด ๊ฒฐ์ œ ์™„๋ฃŒ ์ƒํƒœ์ธ์ง€ ํ™•์ธ

  • ๊ฒฝ์šฐ์— ๋”ฐ๋ผ ์™ธ๋ถ€ API ๋ฅผ ํ˜ธ์ถœํ•˜๊ฑฐ๋‚˜ DB ๋ฅผ ์กฐํšŒํ•˜์—ฌ ๊ฒ€์ฆํ•˜๋Š” ๊ฒฝ์šฐ๋„ ์กด์žฌ

Spring Validation

Java Bean Validation

public class MemberCreationRequest {
		@NotBlank(message="์ด๋ฆ„์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.")
		@Size(max=64, message="์ด๋ฆ„์˜ ์ตœ๋Œ€ ๊ธธ์ด๋Š” 64์ž ์ž…๋‹ˆ๋‹ค.")
    private String name;
		@Min(0, "๋‚˜์ด๋Š” 0๋ณด๋‹ค ์ปค์•ผ ํ•ฉ๋‹ˆ๋‹ค.")
    private int age;
		@Email("์ด๋ฉ”์ผ ํ˜•์‹์ด ์ž˜๋ชป๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
    private int email;

    // the usual getters and setters...
}
  • ์š”์ฒญ dto ์— ์–ด๋…ธํ…Œ์ด์…˜์œผ๋กœ ๋ช…์‹œ ํ›„ @RequestBody ์— @Valid ์–ด๋…ธํ…Œ์ด์…˜์„ ๋‹ฌ๊ฒŒ ๋˜๋ฉด, Java Bean Validation ์ด ์ˆ˜ํ–‰๋˜๊ณ  ๋ฌธ์ œ๊ฐ€ ์—†์„ ๋•Œ๋งŒ ๋ฉ”์„œ๋“œ ๋‚ด๋ถ€๋กœ ์ง„์ž… ๋œ๋‹ค.

  • ๊ฒ€์ฆ ์ค‘ ์‹คํŒจ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด MethodArgumentNotValidException ๋ฐœ์ƒ

@PostMapping(value = "/member")
public MemeberCreationResponse createMember(
	@Valid @RequestBody final MemeberCreationRequest memeberCreationRequest) {
	// member creation logics here...
}

Spring Validator Interface

public class Person {

    private String name;
    private int age;

    // the usual getters and setters...
}
public class PersonValidator implements Validator {

    /**
     * This Validator validates only Person instances
     */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

Person์ด๋ผ๋Š” javaBean ๊ฐ์ฒด๊ฐ€ ์žˆ์„ ๋•Œ, Validator ๋ฅผ ๊ตฌํ˜„ํ•œ PersonValidator ๋ฅผ ํ†ตํ•ด ๊ฒ€์ฆํ•œ๋‹ค.

  • supports validator ๊ฐ€ ๋™์ž‘ํ•  ์กฐ๊ฑด์„ ์ •์˜. ์ฃผ๋กœ class์˜ ํƒ€์ž…์„ ๋น„๊ต

  • validate ๊ฒ€์ฆ์„ ์ง„ํ–‰

์‹ค๋ฌด ํ™œ์šฉ

  1. ์š”์ฒญ dto ์—์„œ Java Bean Validation ์œผ๋กœ 1์ฐจ ๊ฒ€์ฆ

  2. ๋กœ์ง ์ดˆ๊ธฐ์— ๋น„์ฆˆ๋‹ˆ์Šค ๊ฒ€์ฆ ํ›„ Custom Exception ์ฒ˜๋ฆฌ(ErrorCode, ErrorMessage)

  • Spring validator ์žฅ๋‹จ์ 

    • ์žฅ์ : Java Bean Validation ์— ๋น„ํ•ด ์กฐ๊ธˆ ๋” ๋ณต์žกํ•œ ๊ฒ€์ฆ์ด ๊ฐ€๋Šฅ

    • ๋‹จ์ 

      • Validation ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ฐพ๊ธฐ๊ฐ€ ์–ด๋ ต๋‹ค. (์ƒ๋Œ€์ ์œผ๋กœ)

      • ๋น„์ฆˆ๋‹ˆ์Šค ๊ฒ€์ฆ ๋กœ์ง์˜ ํŒŒํŽธํ™” ์œ„ํ—˜.

Last updated