[v3] springboot 블로그 만들기-8
데이터베이스를 조회하지 않고도 정규 표현식을 사용하여 형식을 검사할 수도 있지만
이번에는 ajax 를 사용한 유효성 검사를 해보았다.
Sep 11, 2024
회원가입을 진행할 때 아이디가 중복인지 확인을 하고는 한다.
이는 db에 등록되어 있는 id 와 유저가 입력한 id를 비교하여 동일한게 있는지 확인하는 과정으로 이루어진다.
form 으로 전송할 시 필연적으로 페이지 리로드가 진행됨으로
꼭! 비동기 통신으로 이루어 져야한다.
html 수정
유효성 체크를 위한 버튼 추가


회원가입 버튼이 눌리면
onsubmit
="
return
valid()"
가 실행된다.
이를 통해 중복 체크를 했는지 확인할 것. (true 면 실행, false 면 아무일도 안일어남)<script>
// bool 타입은 is 를 붙여 만든다.
let isSameUsername = true;
function valid(){
if(isSameUsername){
alert("중복체크가 필요합니다.");
return false;
}else {
return true;
}
}
</script>
중복체크 버튼에 sameCheck() 이벤트 추가
<button
onclick
="
sameCheck
()"
type
="button"
class
="btn btn-outline-primary">중복체크</button>
중복체크 버튼 클릭 시 실행될 함수를 만든다.
async function sameCheck() {
// 1. username 가져오기
let username = $("#username").val();
console.log(username);
// 2. fetch로 통신하기
let response =await fetch(`/user/samecheck?username=${username}`);
let responseBody = await response.json();
console.log(responseBody);
// 3. 중복됐으면 isSameUsername = true 프로미스로 받으면 패치댄 해야함 아니면어웨이트
if(responseBody.body){
isSameUsername=true;
alert("중복된 유저네임이에요");
}else {
isSameUsername= false;
alert("가용가능한 이름입니다");
$("#username").attr("readOnly", true);
}
// 4. 중복 안됐으면 = isSameUsername = false; -> username input 을 read Only 로
}
중복되지 않은 아이디인 경우 해당 필드는 수정할 수 없도록 readOnly 한다.
서버 구축
@GetMapping("/user/samecheck")
public ResponseEntity<?> sameCheck(@RequestParam("username") String username){
boolean isSameUsername = userService.유저네임중복되었니(username);
return ResponseEntity.ok(Resp.ok(isSameUsername, isSameUsername ? "중복되었어요" : "중복되지않았어요"));
}
Resp 코드
@AllArgsConstructor
@Data
public class Resp<T> {
private Integer status;
private String msg;
private T body;
public static <B> Resp<?> ok(B body){
return new Resp<>(200, "성공", body);
}
public static <B> Resp<?> ok(B body, String msg){
return new Resp<>(200, msg, body);
}
public static Resp<?> fail(Integer status, String msg){
return new Resp<>(status, msg, null);
}
}
public boolean 유저네임중복되었니(String username) {
Optional<User> userOP = userRepository.findByUsername(username);
if(userOP.isPresent()){
return true;
}else{
return false;
}
}
isPresent
를 사용하여 조회된 userOP 가 비어있는지 확인한다. 비어있지 않다면 true
이므로
조회 요청한 아이디가 true 가 되면 중복되었다는 의미이다.따라서 true → 중복, false → 사용가능 상태가 된다.
3항연산자를 사용하여
return ResponseEntity.ok(Resp.ok(isSameUsername, isSameUsername ? "중복되었어요" : "중복되지않았어요"));
답변을 리턴한다.


리턴된 값의 body 를 보고 후 처리를 하면 완료된다.
마무리
데이터베이스를 조회하지 않고도 정규 표현식을 사용하여 형식을 검사할 수도 있지만
이번에는 ajax 를 사용한 유효성 검사를 해보았다.
다음 포스팅에서는 페이지네이션기능 구현을 해 볼것이다.
SpringBoot 블로그 만들기 - v3 시리즈 1. https://inblog.ai/hj/v3-시작-27809 (개발환경 설정 및 post 맨 이용한 api 테스트) 2. https://inblog.ai/hj/v3-springboot-블로그-만들기-2-28708 (댓글 엔티티 생성 및 양방향 매핑) 3. https://inblog.ai/hj/v3-springboot-블로그-만들기-3-28793 (댓글 조회하기 완료) 4. https://inblog.ai/hj/v3-rest-api-를-위한-exception-설정-28848 (REST API 위한 익셉션 핸들러 구현) 5. https://inblog.ai/hj/v3-springboot-블로그-만들기5-28859 (댓글 삭제 기능 구현) 6. https://inblog.ai/hj/v3-springboot-블로그-만들기6-29071 (ajax 를 사용한 댓글 작성) 7. https://inblog.ai/hj/v3-springboot-블로그-만들기7-29077 (게시물 검색 기능 구현) 8. https://inblog.ai/hj/v3-springboot-블로그-만들기8-29073 (유효성 검사)
Share article