코드이그나이터4 마크다운 블로그 MVP 만들기 - 7 - 유효성 검사 추가하기
이번 예제는 https://github.com/koeunyeon/ci4/commits/blog-validation 에서 찾을 수 있습니다.
유효성 검사 추가하기
우리가 만든 블로그는 유효성 검사를 하지 않습니다. 따라서 처음에 정한 요건인 제목은 4-100글자, 본문은 10-512글자의 규칙을 어겨도 데이터가 입력됩니다.
모델을 통해서 유효성 검사를 추가하겠습니다.
PostsModel.php
클래스에 아래의 코드를 추가합니다.
app/Models/PostsModel.php
protected $validationRules = [
'title' => 'required|min_length[4]|max_length[100]',
'content' => 'required|min_length[10]|max_length[512]',
];
protected $validationMessages = [
'title' => [
'required' => '제목이 필요합니다',
'min_length' => '제목은 최소 4글자 이상입니다.',
'max_length' => '제목은 최대 100글자 이하입니다.'
],
'content' => [
'required' => '본문이 필요합니다',
'min_length' => '본문은 최소 10글자 이상입니다.',
'max_length' => '본문은 최대 512글자 이하입니다.'
],
];
이제 모델은 규칙에 맞지 않으면 데이터를 저장하지 않고 오류를 뱉어냅니다.
컨트롤러에서 모델이 반환한 오류를 처리하도록 수정해 보겠습니다.
생성 엔드포인트 create
는 이미 모델에서 오류를 뱉어낼 경우 처리하는 코드가 있습니다.
app/Controllers/Post.php
$post_id = $model->insert($this->request->getPost());
if ($post_id) { // 모델에서 유효성 검사를 통과할 경우
$this->response->redirect("/post/show/$post_id");
} else { // 모델에서 유효성 검사가 실패하는 경우
return view("/post/create", [
'post_data' => $this->request->getPost(),
'errors' => $model->errors()
]);
}
글 작성시 유효성 체크가 잘 되는지만 http://localhost:8080/post/create 에서 확인해 보겠습니다.
수정에는 오류 처리가 되어 있지 않네요. 추가하겠습니다.
원래 코드는 아래와 같습니다.
$model->update($post_id, $this->request->getPost());
$this->response->redirect("/post/show/$post_id");
아래와 같이 수정하겠습니다.
$isSuccess = $model->update($post_id, $this->request->getPost());
if ($isSuccess){
$this->response->redirect("/post/show/$post_id");
}else{
return view("/post/create", [
'post_data' => $this->request->getPost(),
'errors' => $model->errors()
]);
}
수정 페이지 http://localhost:8080/post/edit 에서 유효성 검사가 작동하는지 검사해 보세요.
Author And Source
이 문제에 관하여(코드이그나이터4 마크다운 블로그 MVP 만들기 - 7 - 유효성 검사 추가하기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@koeunyeon/코드이그나이터4-마크다운-블로그-MVP-만들기-7-유효성-검사-추가하기-수정완료저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)