🎨 form-validator


🪐 logic

  • html内を構成するために必要なform(label-input-smallキットをdivに組み合わせる)
  • error関数/success関数の生成
  • 各形式の検証を設定する
  • (1)(validation)ユーザ名が10文字未満(length)
  • (2)(validation)emailは@となります.com
  • (3)(validation)pw 8文字未満15文字(length)
  • (4)(validation)pw 1とpw 2が一致しているかどうか(length)
  • (5)(validation)値が存在しない場合
  • フォームを提出(クリック)する時、応用完全検証応用イベント
    「コミット」ボタンを押すとvalidatorが有効であればsuccess関数(またはerror関数)を実行し、
    🚀 html
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <link href="index.css" rel="stylesheet" />
            <title>form-validator</title>
        </head>
        <body>
            <div class="container">
                <form id="form">
                    <h1>Sign Up our website</h1>
    
                    <div class="form-control">
                        <label for="username">User Name</label>
                        <input id="username" type="text" placeholder="Enter username" />
                        <small>Error message</small>
                    </div>
    
                    <div class="form-control">
                        <label for="email">Email</label>
                        <input id="email" type="text" placeholder="Enter email" />
                        <small>Error message</small>
                    </div>
    
                    <div class="form-control">
                        <label for="password">Password</label>
                        <input id="password" type="password" placeholder="Enter password" />
                        <small>Error message</small>
                    </div>
    
                    <div class="form-control">
                        <label for="password2">Password Check</label>
                        <input id="password2" type="password" placeholder="Confirm password" />
                        <small>Error message</small>
                    </div>
                    <button id="submit">Submit</button>
                </form>
    
                <script src="index.js"></script>
            </div>
        </body>
    </html>
    🚀 css
    
    @import url("reset.css");
    
    * {
        box-sizing: border-box;
    }
    
    .container {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100vw;
        height: 100vh;
        background-color: cadetblue;
    }
    
    #form {
        padding: 30px;
        max-width: 500px;
        max-height: 800px;
        background-color: #fafafa;
        border: 1px solid tan;
        border-radius: 5px;
        text-align: center;
    }
    
    h1 {
        padding-bottom: 10px;
        color: teal;
        background-color: #fafafa;
        font-size: 30px;
        font-weight: 900;
        text-align: center;
    }
    
    /* form 구성 */
    .form-control {
        display: flex;
        flex-direction: column;
        padding: 10px 0;
        background-color: #fafafa;
    }
    
    small {
        visibility: hidden;  /* small의 defalult는 안보이도록 한다(js를 통해 visible하게 설정 */
        text-align: left;
        font-size: small;
        color: red;
    }
    
    .form-control.error small {
        visibility: visible;
    }
    
    /* input 에 error 및 succecc 적용하는 css */
    .form-control.success input {
        border-color: green;
    }
    
    .form-control.error input {
        border-color: red;
    }
    
    label {
        padding: 10px 0;
        font-weight: 700;
        text-align: left;
    }
    
    input {
        width: 100%;
        padding: 5px 0 5px 10px;
        cursor: text;
    }
    
    #submit {
        margin: 10px;
        padding: 5px 10px;
        color: #fafafa;
        background-color: teal;
        border: 1px solid teal;
        border-radius: 5px;
        cursor: pointer;
    }
    🚀 js
    
    "use strict";
    
    const userName = document.getElementById("username");
    const email = document.getElementById("email");
    const pw1 = document.getElementById("password");
    const pw2 = document.getElementById("password2");
    const form = document.getElementById("form");
    
    // error 표시 구현 기능(error 메시지 포함)
    function showError(input, message) {
        // input.parentElement = form-control
        const formControl = input.parentElement;
        formControl.className = "form-control error";
    
        const small = formControl.querySelector("small"); // 지역변수로 선언해줘야 한다
        small.innerText = message;
    }
    
    // success 표시 구현 기능
    function showSuccess(input) {
        const formControl = input.parentElement;
        formControl.className = "form-control success";
    }
    
    // label의 첫 글자를 대문자로 변환
    function idName(input) {
        return input.id.charAt(0).toUpperCase() + input.id.slice(1);
    }
    
    // (validation) input 값 길이(length) 유효성 검사 (username && password)
    function checkLength(input, min, max) {
        if (input.value.length < min) {
            showError(input, `${idName(input)} must be at least ${min} characters`);
        } else if (input.value.length > max) {
            showError(input, `${idName(input)} must be less than ${max} characters`);
        } else {
            showSuccess(input);
        }
    }
    
    // (validation) email 유효성 검사
    function checkEmail(input) {
        if (input.value.trim() && input.value.includes("@")) {
            showSuccess(input);
        } else {
            showError(input, `${idName(input)} is not valid`);
        }
    }
    
    // (validation) Check passwords match
    function checkPasswordsMatch(input1, input2) {
        if (input1.value !== input2.value) {
            showError(input2, "Passwords do not match");
        }
    }
    
    // 값이 없을 때
    function checkRequired(inputArr) {
        // 모든 input값에 다 해당하므로 배열 형태로 매개변수 넣어줌
        let isRequired = false;
        inputArr.forEach(function (input) {
            if (input.value.length < 0) {
                //값이 없으면
                showError(input, `${idName(input)} is required`);
                isRequired = true;
            } else {
                showSuccess(input);
            }
        });
    
        return isRequired;
    }
    
    // 위의 함수들을 실행시켜줄 addEventListner 걸어주기 (form 에 걸어주기)
    form.addEventListener("submit", function (e) {
        e.preventDefault(); // 유효성 검사가 실행되기도 전에, submit 되는 것을 막아줌
    
        if (!checkRequired([userName, email, pw1, pw2])) {
            // value가 존재한다면
            checkLength(userName, 3, 15);
            checkLength(pw1, 6, 25);
            checkEmail(email);
            checkPasswordsMatch(pw1, pw2);
        }
    });