JavaScript Form Validation - Custom Validation Functions
Form validation is a crucial part of creating user-friendly and secure web applications. In JavaScript, you can implement custom validation functions to ensure that user input meets specific requirements. In this guide, we'll explore how to create custom validation functions and integrate them into your web forms with practical examples.
HTML Form Structure
First, let's set up a simple HTML form that we'll use for validation:
<form id="myForm" onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<div class="error-message" id="nameError"></div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<div class="error-message" id="emailError"></div>
<input type="submit" value="Submit">
</form>
Custom Validation Functions
Now, let's define custom validation functions using JavaScript. These functions will be responsible for checking the validity of the user input. For example, we'll create a custom function to check if the name field contains only alphabetic characters:
function isNameValid(name) {
return /^[A-Za-z]+$/.test(name);
}
Similarly, we'll create a custom function to validate email addresses using a regular expression:
function isEmailValid(email) {
return /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/.test(email);
}
Form Validation Function
Next, we'll create a validation function that will be triggered when the form is submitted. This function will use the custom validation functions to check the user input:
function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const nameError = document.getElementById('nameError');
const emailError = document.getElementById('emailError');
nameError.textContent = '';
emailError.textContent = '';
let isValid = true;
if (!isNameValid(name)) {
nameError.textContent = 'Name must contain only alphabetic characters.';
isValid = false;
}
if (!isEmailValid(email)) {
emailError.textContent = 'Invalid email address.';
isValid = false;
}
return isValid;
}
Conclusion
Custom validation functions in JavaScript allow you to define specific validation rules for your web forms. By creating these functions and integrating them into your form submission process, you can ensure that user input meets your application's requirements and provide meaningful error messages when validation fails.
Happy coding with JavaScript form validation and custom validation functions!