DEV Community

loading...

Validate a simple form using RegEx

Osinachi Chukwujama
Learning server-side development. Creating courses on educative.io
・3 min read

In this tutorial, we would be creating a form and validating its values using regular expressions

Creating the markup

The markup would be really simple. Just plain HTML with a few input tags

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>RegEx Form</title>
        <link rel="stylesheet" href="./styles.css">
    </head>
    <body>
        <h1>New User Signup</h1>
        <form>

            <input type="text" name="username" placeholder="username">
            <p>Username must be lowercase including numbers and contain 5 - 12 characters</p>

            <input type="text" name="email" placeholder="email">
            <p>Email must be a valid address, e.g. me@mydomain.com</p>

            <input type="password" name="password" placeholder="password">
            <p>Password must alphanumeric (@, _ and - are also allowed) and be 8 - 20 characters</p>

            <input type="text" name="telephone" placeholder="telephone">
            <p>Telephone must be a valid 11 digits telephone number</p>

        </form>
        <script type="text/javascript" src="./validation.js"></script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

From the markup, there are four input fields to be validated

  1. username:
    1. Must contain only lowercase alphabets
    2. Can contain digits
    3. Allows from 5 to 12 characters
    4. Would be case insensitive
  2. email:
    1. Must contain the name
    2. Must contain the @ and .
    3. Must contain the domain
    4. Must contain the extension, which could have a child extension (e.g .co.uk)
  3. password
    1. Can contain @, _ and -
    2. Must be 8 to 20 characters long
  4. telephone
    1. Must contain 11 digits only

A little css would help

body{
    font-family: arial;
    color: #333;
}
h1{
    font-weight: normal;
    margin: 20px auto;
    text-align: center;
}
form{
    width: 90%;
    margin: 20px auto;
}
input{
    display: block;
    padding: 8px 16px;
    font-size: 2em;
    margin: 10px auto;
    width: 100%;
    box-sizing: border-box;
    border-radius: 10px;
    border: 3px solid #ccc;
    outline: none !important;
}
.valid {
    border-color: #36cc36;
}
.invalid {border-color:orange}

input + p {
    font-size: 0.9em;
    font-weight: bold;
    margin: 0 10px;
    text-align: center;
    color: orange;
    opacity: 0;
    height: 0;
}
input.invalid + p {
    opacity: 1;
    height: auto;
    margin-bottom: 20px;
}
Enter fullscreen mode Exit fullscreen mode

This add a little flavor and gives each field a valid/invalid class style depending on the case.

Unto the main stuff

The validation would be achieved using JavaScript (obviously).
We begin by defining each regex for each input field. But this would be done using an object, to contain everything.

const input_fields = {
  username: /^[a-z\d]{5,12}$/i,
  email: /^([a-z\d\.-]+)@([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/,
  password: /^[#\w@_-]{8,20}$/,
  telephone:/^\d{11}$/,
}
Enter fullscreen mode Exit fullscreen mode

What's going on?

  1. The username regex must begin and end with values defined by the character class [a-z\d]{5,12}. This means, 5 to 12 characters that are lower-case letters or digits. The ^ and $ indicate that the expression starts and ends with those characters. Nothing can precede to come after them. The i after the regex indicates that it should be case-insensitive.
  2. The email regex has six parts.
    1. The name: lower-case letters, hyphens, dots or digits with one or more characters indicated by the +. They are enclosed by parenthesis to group them.
    2. The @ symbol follows afterwards
    3. The domain name should contain one or more lower-case characters, digits or hyphens
    4. The dot follows. Its special meaning is overwritten by backslash
    5. The first extension contains 2 to 8 characters
    6. The second is optional, indicated by ?. Same rules as the first
  3. The password contains any word character \w (letters and digits). # _ - @ are also supported.
  4. The telephone number is an 11 digit number

We can now define a validate function which will handle our validation

const validate = (field, regex) => {
  regex.test(field.value) ? field.className = 'valid' : field.className = 'invalid';
}
Enter fullscreen mode Exit fullscreen mode

We define a new function called validate having two parameters, field and regex. The regex.test() method is called on the field's value and checked using the tenary operator.

let keys = document.querySelectorAll('input');
keys.forEach(item => item.addEventListener(
  'keyup', e => {
    validate(e.target, input_fields[e.target.attributes.name.value])
  }
));
Enter fullscreen mode Exit fullscreen mode

Finally, we select all the input elements and give them a keyup event. The validate function on the particular input field which we are typing in.
The validate function acts as the callback and has the particular field as the first argument and its corresponding key from the input_fields object as its second.

e.target.attributes.name.value
//this gets the target field and goes to its attributes 
//for the name attribute and checks the value of that.
Enter fullscreen mode Exit fullscreen mode

Conclusion

We successfully used regular expression to validate a form. If you are totally lost, I recommend that you google more about regular expressions.
The sample code can be downloaded from my github repo

https://github.com/Vicradon/regex-validation

Discussion (0)