This is JavaScript Form Validation Tutorial. JavaScript form validation is the process of checking that the data entered into a form by a user is valid before it is submitted to the server. Form validation can be used to ensure that required fields are filled out, that data is entered in the correct format, and that the data meets certain criteria, such as minimum and maximum length.
Basic JavaScript Form Validation Tutorial:
- Add an event listener to the form’s “submit” event. This will allow you to perform validation checks before the form is submitted.
document.getElementById("myForm").addEventListener("submit", validateForm);
- Create a function called “validateForm” that will contain the validation logic.
function validateForm(event) {
event.preventDefault(); // prevent the form from submitting
// perform validation checks here
}
- Use the “value” property of the form elements to access the data entered by the user.
Copy codelet name = document.getElementById("name").value;
- Use JavaScript’s built-in string methods, such as “length” and “indexOf” to check the length of the input and whether it contains certain characters.
if (name.length < 3) {
alert("Name must be at least 3 characters long");
return false;
}
- Use the “classList” property to add and remove CSS classes to indicate whether an input is valid or not.
if (name.length < 3) {
document.getElementById("name").classList.add("is-invalid");
} else {
document.getElementById("name").classList.remove("is-invalid");
}
- Use the built-in JavaScript functions such as parseInt() or parseFloat() to validate numbers.
let age = parseInt(document.getElementById("age").value);
if (isNaN(age) || age < 18) {
alert("Age must be a number and at least 18");
return false;
}
Here’s an example of a basic HTML form with a text box and JavaScript validation for that text box:
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" required>
<br>
<button type="submit">Submit</button>
</form>
// Add event listener to form's submit event
document.getElementById("myForm").addEventListener("submit", validateForm);
function validateForm(event) {
event.preventDefault(); // prevent the form from submitting
// Name validation
let name = document.getElementById("name").value;
if (name.length < 3) {
alert("Name must be at least 3 characters long");
return false;
}
}
In this example, the JavaScript function “validateForm” is attached to the form’s “submit” event. The function prevents the form from submitting if the validation checks fail. The validation check in this example is for the “name” input field, it checks if the length of the input is less than 3 characters, if so it will show an alert message and the form will not be submitted.