JavaScript can be used to validate data in an HTML form before it is sent to a server. This improves security and provides a better experience for the user.
You can check if a field is empty when the user clicks the "Submit" button by using the
onsubmit event attribute of the form.
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false; // Prevents form from submitting
}
}
In the HTML, you would call this function like so:
<form name="myForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
The document.forms collection allows you to access any form by its name or ID,
and then target specific input fields within it.
const userEmail = document.forms["register"]["email"].value;
Modern browsers have a built-in Constraint Validation API that provides powerful properties and methods for professional validation:
checkValidity(): Returns true if an input
element contains valid data.setCustomValidity(): Sets the validation message (useful
for custom rules).validationMessage: Returns the error message displayed to
the user.JavaScript works alongside HTML5 attributes to enforce rules:
disabled: Field is not processed.max / min: Sets a numeric range.pattern: Defines a regular expression (RegExp) pattern.
required: Field must be filled in.onsubmit to trigger validation logicfalse stops the form from submittingdocument.forms or standard selection
methods