🎒내가방/📒JavaScript

[자바스크립트] 회원가입 할 때 패스워드 체크 기능 구현하기

2023. 6. 29. 16:53
목차
  1. 회원가입 시 비밀번호 유효성 검사하기
  2. 전체 JS 코드

회원가입을 할 때 패스워드 유효성 체크 하는 기능을 구현해 보았다.

레이아웃은 'Bulma'(https://bulma.io/documentation/form/general/)에서 가져오고 유효성 체크 기능은 자바스크립트를 활용했다.

 

회원가입 레이아웃

<HTML 코드>

  • input 태그의 id 값과 label 태그의 for 속성을 일치시켜 준다.
더보기
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원가입</title>
    <!-- css -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
    <link rel="stylesheet" href="./style.css">
    <!-- js -->
    <script defer src="./index.js"></script>
</head>
<body>
<div id = "wrap">
    <div class="field">
  <label class="label" for="nameInput">이름</label>
  <div class="control">
    <input class="input" type="text" placeholder="" id="nameInput">
  </div>
</div>

<div class="field">
  <label class="label" for="usernameInput">닉네임</label>
  <div class="control has-icons-left has-icons-right">
    <input class="input is-success" type="text" placeholder="Text input" value="bulma" id="usernameInput">
    <span class="icon is-small is-left">
      <i class="fas fa-user"></i>
    </span>
    <span class="icon is-small is-right">
      <i class="fas fa-check"></i>
    </span>
  </div>
  <p class="help is-success">사용 가능한 닉네임 입니다.</p>
</div>

<div class="field">
    <label class="label" for="passwordInput">비밀번호</label>
    <div class="control has-icons-left has-icons-right">
      <input class="input is-success" type="password" placeholder="Text input" value="bulma" id="passwordInput">
      <span class="icon is-small is-left">
        <i class="fas fa-user"></i>
      </span>
      <span class="icon is-small is-right">
        <i class="fas fa-check"></i>
      </span>
    </div>
</div>

<div class="field">
    <label class="label" for="passwordConfirmInput">비밀번호 확인</label>
    <div class="control has-icons-left has-icons-right">
      <input class="input is-success" type="password" placeholder="Text input" value="bulma" id="passwordConfirmInput">
      <span class="icon is-small is-left">
        <i class="fas fa-user"></i>
      </span>
      <span class="icon is-small is-right">
        <i class="fas fa-check"></i>
      </span>
    </div>
</div>

<div class="field">
  <label class="label" for="emailInput">이메일</label>
  <div class="control has-icons-left has-icons-right">
    <input class="input is-success" type="email" placeholder="Email input" value="hello@" id="emailInput">
    <span class="icon is-small is-left">
      <i class="fas fa-envelope"></i>
    </span>
    <span class="icon is-small is-right">
      <i class="fas fa-exclamation-triangle"></i>
    </span>
  </div>
  <!-- <p class="help is-danger">사용할 수 없는 이메일 입니다.</p> -->
</div>

<div class="field">
  <label class="label" for="subjectSelect">성별</label>
  <div class="control">
    <div class="select">
      <select id="subjectSelect">
        <option>여</option>
        <option>남</option>
      </select>
    </div>
  </div>
</div>

<div class="field">
  <div class="control">
    <label class="checkbox">
      <input type="checkbox">
       <a href="#">회원 가입 약관 동의</a>합니다.
    </label>
  </div>
</div>

<div class="field">
  <div class="control">
    <label class="radio">
      <input type="radio" name="question">
      Yes
    </label>
    <label class="radio">
      <input type="radio" name="question">
      No
    </label>
  </div>
</div>

<div class="field is-grouped">
  <div class="control">
    <button class="button is-link" id="submitButton">가입하기</button>
  </div>
  <div class="control">
    <button class="button is-link is-light">뒤로가기</button>
  </div>
</div>
</div>
</body>
</html>

 

<CSS 코드>

더보기
/* join */
#wrap{width:800px; margin:0 auto; padding-top: 50px;}

 

회원가입 시 비밀번호 유효성 검사하기

 

1. HTML 문서에서 필요한 요소들을 querySelector를 사용하여 선택

  • 제출 버튼(submitButton)에 클릭 이벤트 리스너를 추가하여 handleSubmit 함수가 호출되도록 설정

 

// 요소들 모음
const nameInput = document.querySelector('#nameInput')
const usernameInput = document.querySelector('#usernameInput')
const emailInput = document.querySelector('#emailInput')
const passwordInput = document.querySelector('#passwordInput')
const passwordConfirmInput = document.querySelector('#passwordConfirmInput')
const submitButton = document.querySelector('#submitButton')

// 이벤트 추가
submitButton.addEventListener('click', handleSubmit)

 

2. handleSubmit 함수는 이벤트 객체(e)를 매개변수로 받고, e.preventDefault()를 호출하여 기본 제출 동작 방지

  • e.preventDefault -  브라우저가 적용하는 기본 동작을 방지하는 역할
async function handleSubmit(e) {
  // preventDefault 안 하면 새로고침됨.
  e.preventDefault

 

3. 각 입력 필드의 값을 가져와 변수에 할당

// 입력값 가져오기
  const fullName = nameInput.value
  const nickname = usernameInput.value
  const email = emailInput.value
  const password = passwordInput.value
  const passwordConfirm = passwordConfirmInput.value

 

4. 비밀번호와 비밀번호 확인이 일치하는지 확인하고, 일치하지 않으면 알림 발생

// 비밀번호 비교
  if (password !== passwordConfirm) {
    return alert("비밀번호가 일치하지 않습니다.")
  } 

  if (!isValidEmail(email)) {
    return alert('올바른 이메일 형식이 아닙니다.');
  }

 

5. 사용자 입력 데이터를 객체로 생성하고, JSON.stringify를 사용하여 JSON 형태로 변환

  • API 엔드포인트 주소를 변수로 지정하고, fetch를 사용하여 POST 요청을 보냄
  • 응답 상태 코드(res.status)를 확인하여 성공 또는 실패 여부에 따라 알림 발생
// 객체 만듦
   const data = {
    fullName,
    nickname,
    email,
    password
  }
  
  // JSON 만듦
  const dataJson = JSON.stringify(data)
  
  const apiUrl = `https://${window.location.hostname}:8190/api/register`

  const res = await fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: dataJson,
  });
  
  if (res.status === 201) {
    alert("회원가입에 성공하였습니다!")
  } else {
    alert("회원가입에 실패하였습니다...")
  }

 

6. (추가) 이메일의 유효성을 확인하는 isValidEmail 함수를 구현하기

function isValidEmail(email) {
    const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return emailRegex.test(email);
  }

 

전체 JS 코드

더보기

const nameInput = document.querySelector('#nameInput')
const usernameInput = document.querySelector('#usernameInput')
const emailInput = document.querySelector('#emailInput')
const passwordInput = document.querySelector('#passwordInput')
const passwordConfirmInput = document.querySelector('#passwordConfirmInput')
const submitButton = document.querySelector('#submitButton')

submitButton.addEventListener('click', handleSubmit)

async function handleSubmit(e) {
  // preventDefault 안 하면 새로고침됨.
  e.preventDefault
  
  const fullName = nameInput.value
  const nickname = usernameInput.value
  const email = emailInput.value
  const password = passwordInput.value
  const passwordConfirm = passwordConfirmInput.value
    
  if (password !== passwordConfirm) {
    return alert("비밀번호가 일치하지 않습니다.")
  } 

  if (!isValidEmail(email)) {
    return alert('올바른 이메일 형식이 아닙니다.');
  }

   const data = {
    fullName,
    nickname,
    email,
    password
  }
  
  const dataJson = JSON.stringify(data)
  
  const apiUrl = `https://${window.location.hostname}:8190/api/register`

  const res = await fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: dataJson,
  });
  
  if (res.status === 201) {
    alert("회원가입에 성공하였습니다!")
  } else {
    alert("회원가입에 실패하였습니다...")
  }
  
 
}

function isValidEmail(email) {
    const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return emailRegex.test(email);
  }

 

저작자표시 (새창열림)

'🎒내가방 > 📒JavaScript' 카테고리의 다른 글

[자바스크립트] 상품을 필터링하기  (1) 2023.07.01
[자바스크립트] 상품 목록 가져오기  (0) 2023.07.01
[모던 자바스크립트 Deep Dive] 18장 함수와 일급객체  (1) 2023.06.29
[모던 자바스크립트 Deep Dive] 17장 생성자 함수에 의한 객체 생성  (0) 2023.06.29
[자바스크립트] 스코프  (0) 2023.06.22
  1. 회원가입 시 비밀번호 유효성 검사하기
  2. 전체 JS 코드
'🎒내가방/📒JavaScript' 카테고리의 다른 글
  • [자바스크립트] 상품을 필터링하기
  • [자바스크립트] 상품 목록 가져오기
  • [모던 자바스크립트 Deep Dive] 18장 함수와 일급객체
  • [모던 자바스크립트 Deep Dive] 17장 생성자 함수에 의한 객체 생성
멍발윤
멍발윤
개발 노트
멍발윤
윥이 개발노트
멍발윤
전체
오늘
어제
  • my (37)
    • 🎒내가방 (33)
      • 📒JavaScript (22)
      • 📒jQuery (2)
      • 📒React (7)
      • 📒Spring (2)
    • 📓일상 (0)
      • ✏️끄적끄적 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 회원가입만들기
  • CSS
  • 프로그래머스
  • 멋사
  • 엘리스코딩
  • 사직후기
  • 프로젝트 모집
  • 비밀번호 유효성 검사
  • 바닐라익스트랙트
  • 리액트
  • sw엔지니어트랙
  • 자바스크립트
  • 티스토리챌린지
  • cssinjs
  • 비전공자개발자
  • 엘리스5기
  • 프로그래머스스쿨
  • 일조집
  • 구월의마카롱
  • 오블완

최근 댓글

최근 글

hELLO · Designed By 정상우.
멍발윤
[자바스크립트] 회원가입 할 때 패스워드 체크 기능 구현하기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.