Craft Powerful Form Validations Using Regular Expressions in HTML5
Working with forms are very essential one in terms of web development. In html, javascript, react, laravel, or any framework you work in, as a developer you do not only need to understand the form submission techniques, but also validating the form in the effective way. You can go for different techniques to achieve a good validation performance. Whether you work in a framework or use any package, knowing the basics in html or javascript will help you anywhere to fit in. In Html5, there are some basic validations in form is provided, which you can use anytime where you have to add some quick validation in the form fields. Apart from that, for any custom validation, you might use pattern validation for your convenience. In this article we will see some demo how we can use this technique efficiently.
Typical form validation ways
Normally, for simple form validation, you might use validation attributes available for that input tag in form. For example, for a required type validation, you might use this:
<form>
<label for="username">Username (required):</label>
<input type="text" id="username" name="username" required>
<input type="submit" value="Submit">
</form>
For a email type validation you can just use the type=”email”:
<form>
<label for="email">Email (required and must be a valid email address):</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
How to do pattern validation?
We can also set pattern for our input fields to validate the data. These type of validations will require a regexp (regular expression) to match if the values in the inputs are correct. For example, if you need to validate a phone number like 123-456-7890, you might set the value in the pattern attribute like this:
<form>
<label for="phone">Phone Number (required, format: 123-456-7890):</label>
<input type="tel" id="phone" name="phone" pattern="\d{3}-\d{3}-\d{4}" required>
<small>Format: 123-456-7890</small>
<input type="submit" value="Submit">
</form>
This pattern will ensure that the phone number before and after first dash(-), will be 3 digit from the user and 4 digit after 2nd dash(-)
Thus you can make a quick validation logic just with some regular expression.
Custom validation using patterns
So as you can see, this regular expressions are dynamic, which depends on your / client’s preference, you can make any custom validation logic upon this.
Password validation example: A common example can be validating passwords, like we often want our password fields should be one letter and one number and at least 8 characters long. We can also do that with pattern validation like below:
<form>
<label for="password">Password (required, minimum 8 characters, at least one letter and one number):</label>
<input type="password" id="password" name="password" pattern="(?=.*\d)(?=.*[a-zA-Z]).{8,}" required>
<small>Must contain at least one letter and one number, and be at least 8 characters long</small>
<input type="submit" value="Submit">
</form>
Prevent empty field submission: Sometimes you might have added required to a input field, but still users might can submit the form with just giving some spaces, and the default html validation wont able to validate that. These kind of approach are often common in spammers or data scraping bots.
We can also use regular expression for validating such cases:
<form action="/submit" method="POST">
<!-- Required Name Field (no spaces only) -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required
pattern=".*\S.*" title="This field cannot be empty or contain only spaces">
<br><br>
<input type="submit" value="Submit">
</form>
Here in the pattern, we are stating that this field cant have only spaces, users have to type at least a single character and also we are setting a custom message with the title attribute.
For textarea validation
The pattern validation works for most of the input fields but for textarea, it doesnt work. But devs know we often use textarea as a input field in many forms. For that, we can use bit javascript to achieve same sort of validation:
<form id="myForm" action="/submit" method="POST">
<!-- Textarea Field -->
<label for="message">Message:</label>
<textarea id="message" name="message" required title="This field cannot be empty or contain only spaces"
onchange="validateTextarea()"></textarea>
<br><br>
<button type="submit" id="submitBtn">Submit</button>
</form>
<script>
// Function to validate textarea
function validateTextarea() {
var textarea = document.getElementById('message');
var message = textarea.value.trim(); // Remove leading and trailing spaces
if (!message.trim()) {
event.target.setCustomValidity("This field cannot contain only spaces");
event.target.reportValidity();
} else {
event.target.setCustomValidity("");
event.target.reportValidity();
}
}
</script>
As the pattern validation doesnt work for textarea, we are using a custom javascript function on change, where if there is no character except only spaces are provided, we are showing user a custom error with setCustomValidity and reportValidity.
Summary
We can use different package or library for doing smarter validations, there are plenty available in the internet. But sometimes knowing these basics will always help you to boost your workflow. For any simple forms, where you dont need to do a heavy validation, you can just quickly add some regular expression logic and validate form faster.
So thats all from here today. Please let me know your thoughts in the comments and give a love to this article if you found this helpful.
Will see you on the next article.
Comments