> For the complete documentation index, see [llms.txt](https://injun-woo30000.gitbook.io/growth-log/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://injun-woo30000.gitbook.io/growth-log/i-learned/ruby-on-rails/perfect-ruby-on-rails/undefined-3.md).

# 모델 개발 - 유효성 검사 구현

보통 클라이언트 측에서 유효성 검사를 할 때는 자바스크립트 라이브러리를 사용한다. 근데 이는 자바스크립트 기능을 꺼버리면 손쉽게 무시할 수 있다. 따라서 일단 클라이언트에서 예비 유효성 검사를 수행하여 유효성 검사마다 통신이 발생하는 낭비를 막고, 서버에서는 최종적인 검사를 한 번 더 수행하는 것이 일반적이다.

검사 규칙은 `validates` 메서드를 사용하면 된다. 참고로 Rails에서 정규식을 쓸 때는 `^`과 `$`을 `\A`와 `\z` 기호를 사용한다.

입력항목을 공백으로 두었을 때 여러 항목의 유효성 검사 결과가 경고창으로 한번에 표시되면 필요 이상으로 많은 오류가 출력되어 왜 오류가 나는지 근본적인 원인을 찾아내기 어려워진다.

`allow_nil` 과 `allow_blank` 옵션을 잘 사용해보자.

`if`와 `unless` 옵션을 아래처럼 이용하면 메일 수신 동의(dm)을 체크했을 때만 메일 주소 기입이 필수가 되도록 만들 수 있다.

```
class User < ActiveRecord::Base
  validates :email, presence: { unless: 'dm.blank?'}
end
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://injun-woo30000.gitbook.io/growth-log/i-learned/ruby-on-rails/perfect-ruby-on-rails/undefined-3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
