This article focuses on how to use JavaScript native forms for form validation. The project address

Create related files

Create index.html, main.js, and styles. CSS files in VSCode:

Initialize related files

To add the relevant structure to the HTML file, start using the Live Server plug-in:

<! DOCTYPEhtml>
<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">
    <title>Form Validation</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.css" rel="stylesheet">
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
    <section class="container">
        <div class="header">
            <h2>Create account</h2>
        </div>
    </section>
    <script src="./main.js"></script>
</body>
</html>
Copy the code

You can see the introduction of font-awesome for easy presentation of charts.

Adding form elements

Add form controls and corresponding submit buttons, etc:

<form id="form" class="form">
  <div class="form-control">
    <label for="username">The user name</label>
    <input type="text" id="username" placeholder="Enter a user name" />
    <i class="fas fa-check-circle"></i>
    <i class="fas fa-exclamation-circle"></i>
    <small>The error message</small>
  </div>
  <div class="form-control">
    <label for="email">Email address</label>
    <input type="text" id="email" placeholder="Enter mailbox" />
    <i class="fas fa-check-circle"></i>
    <i class="fas fa-exclamation-circle"></i>
    <small>The error message</small>
  </div>
  <div class="form-control">
    <label for="password">password</label>
    <input type="password" id="password" placeholder="Enter your password" />
    <i class="fas fa-check-circle"></i>
    <i class="fas fa-exclamation-circle"></i>
    <small>The error message</small>
  </div>
  <div class="form-control">
    <label for="confirm-password">Confirm password</label>
    <input type="password" id="confirm-password" placeholder="Confirm password" />
    <i class="fas fa-check-circle"></i>
    <i class="fas fa-exclamation-circle"></i>
    <small>The error message</small>
  </div>
  <button>submit</button>
</form>
Copy the code

Setting layout Styles

Set the layout of the form to look nice:

@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');

* {
    box-sizing: border-box;
}

body {
    background-color: #ffc600;
    font-family: 'Poppins', sans-serif;
    display: grid;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    margin: 0;
}

.container {
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0.0.0.3);
    overflow: hidden;
    width: 400px;
    max-width: 100%;
}

.header {
    border-bottom: 1px solid #f0f0f0;
    background-color: #4b88fb;
    color: #fff;
    padding: 20px 40px;
}

.header h2 {
    margin: 0;
}

.form {
    padding: 30px 40px;
}

.form button {
    background-color: #4b88fb;
    border: 2px solid #4b88fb;
    border-radius: 4px;
    color: #fff;
    display: block;
    font-family: inherit;
    font-size: 16px;
    padding: 10px;
    margin-top: 20px;
    width: 100%;
}

.form-control {
    margin-bottom: 10px;
    padding-bottom: 20px;
    position: relative;
}

.form-control label {
    display: inline-block;
    margin-bottom: 5px;
}

.form-control input {
    border: 2px solid #f0f0f0;
    border-radius: 4px;
    display: block;
    font-family: inherit;
    font-size: 14px;
    padding: 10px;
    width: 100%;
}

.form-control input:focus {
    outline: 0;
    border-color: # 777;
}


Copy the code

Now our form style is changed to:

Now let’s test the style in case of both successful and failed validation (temporary validation style) :

Add success or error classes to form-Control, respectively:

  <div class="form-control success">
    <label for="username">The user name</label>
    <input type="text" id="username" placeholder="Enter a user name" />
    <i class="fas fa-check-circle"></i>
    <i class="fas fa-exclamation-circle"></i>
    <small>The error message</small>
  </div>
  <div class="form-control error">
    <label for="email">Email address</label>
    <input type="text" id="email" placeholder="Enter mailbox" />
    <i class="fas fa-check-circle"></i>
    <i class="fas fa-exclamation-circle"></i>
    <small>The error message</small>
  </div>
Copy the code

Add the appropriate style to the style file:

.form-control.success input {
    border-color: #2ecc71;
}

.form-control.error input {
    border-color: #e74c3c;
}
Copy the code

You can see:

As expected, remove the SUCCESS and error classes from from-Control.

We then control the corresponding icon to display at the correct time through the style:

.form-control i {
    visibility: hidden;
    position: absolute;
    top: 40px;
    right: 10px;
}

.form-control.success i.fa-check-circle {
    color: #2ecc71;
    visibility: visible;
}

.form-control.error i.fa-exclamation-circle {
    color: #e74c3c;
    visibility: visible;
}

.form-control small {
    color: #e74c3c;
    position: absolute;
    bottom: 0;
    left: 0;
    visibility: hidden;
}

.form-control.error small {
    visibility: visible;
}
Copy the code

The validation logic

The first is to verify the user name input, can not enter blank:

const form = getElementById('form');
const username = getElementById('username');
const email = getElementById('email');
const password = getElementById('password');
const confirmPassword = getElementById('confirm-password')

form.addEventListener('submit'.e= > {
    e.preventDefault();

    const usernameValue = username.value.trim();
		
    if (usernameValue === ' ') {
        setErrorFor(username, 'User name cannot be empty')}else{ setSuccessFor(username); }});function setErrorFor(input, message) {
    const formControl = input.parentElement;
    const small = formControl.querySelector('small');
    formControl.className = 'form-control error';
    small.innerText = message;
}

function setSuccessFor(input) {
    const formControl = input.parentElement;
    formControl.className = 'form-control success';
}

function getElementById(id) {
    return document.getElementById(id)
}
Copy the code

When you click “Submit” with an empty username, you will get an error:Similarly, email is validated, but the mailbox is validated using regular expressions (more on regular expressions can be found hereReference here)

// ...
form.addEventListener('submit'.e= > {
    e.preventDefault();

    // ...
		const emailValue = email.value
    
    if (emailValue === ' ') {
        setErrorFor(email, 'Email address cannot be empty');
    } else if(! isEmail(emailValue)) { setErrorFor(email,'Incorrect email address');
    } else {
        setSuccessFor(email)
    }
    / /...
});

function isEmail(email) {
  return /[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/.test(email)
}
Copy the code

Now verify the two password input fields:

form.addEventListener('submit'.e= > {
    e.preventDefault();

    / /...
    const passwordValue = password.value.trim();
    const confirmPasswordValue = confirmPassword.value.trim();

    if (passwordValue === ' ') {
        setErrorFor(password, 'Password cannot be empty');
    } else {
        setSuccessFor(password)
    }

    if (confirmPasswordValue === ' ') {
        setErrorFor(confirmPassword, 'Confirm password cannot be empty')}else if(passwordValue ! == confirmPasswordValue) { setErrorFor(confirmPassword,'Passwords do not match twice')}else {
        setSuccessFor(confirmPassword)
    }
  	/ /...
});
Copy the code

At this point, to verify in general, enter incorrect form information:And correct form information after modification

conclusion

This form verification is simply verified when clicking the “submit” button. Of course, the experience will not be very good, and this method is rarely used in actual production, but the basic idea is the same.