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>
From the markup, there are four input fields to be validated
- username:
- Must contain only lowercase alphabets
- Can contain digits
- Allows from 5 to 12 characters
- Would be case insensitive
- email:
- Must contain the name
- Must contain the @ and .
- Must contain the domain
- Must contain the extension, which could have a child extension (e.g .co.uk)
- password
- Can contain @, _ and -
- Must be 8 to 20 characters long
- telephone
- 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;
}
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}$/,
}
What's going on?
- 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. - The email regex has six parts.
- 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. - The @ symbol follows afterwards
- The domain name should contain one or more lower-case characters, digits or hyphens
- The dot follows. Its special meaning is overwritten by backslash
- The first extension contains 2 to 8 characters
- The second is optional, indicated by
?
. Same rules as the first
- The name: lower-case letters, hyphens, dots or digits with one or more characters indicated by the
- The password contains any word character
\w
(letters and digits).# _ - @
are also supported. - 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';
}
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])
}
));
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.
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
Top comments (0)