Forms API
JavaScript Constraint Validation API
Section titled “JavaScript Constraint Validation API”HTML5 introduced the Constraint Validation API, which allows browsers to validate form input natively based on attributes set on form elements. JavaScript can interact with this API to check validity and customize validation messages.
Key HTML Input Attributes for Validation
Section titled “Key HTML Input Attributes for Validation”These attributes enable built-in browser validation:
required: Specifies that an input field must be filled out.type: (e.g.,email,url,number,date) Provides inherent validation for the format.minandmax: Specify minimum and maximum values for number or date inputs.minlengthandmaxlength: Specify minimum and maximum length for text inputs.pattern: Specifies a regular expression that the input’s value must match.
Example HTML Form with Validation Attributes:
<form id="myForm"> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <br><br> <label for="age">Age (18-99):</label> <input type="number" id="age" name="age" min="18" max="99" required> <br><br> <label for="password">Password (min 8 chars, 1 number, 1 uppercase):</label> <input type="password" id="password" name="password" minlength="8" pattern=".*(?=.*\d)(?=.*[A-Z]).*" title="Must contain at least one number, one uppercase letter, and at least 8 characters." required> <br><br> <button type="submit">Submit</button></form><p id="errorMessage" style="color: red;"></p>When a user tries to submit a form with invalid data based on these attributes, the browser typically prevents submission and displays a default error message.
Constraint Validation DOM Methods and Properties
Section titled “Constraint Validation DOM Methods and Properties”JavaScript provides methods and properties on input elements to interact with their validity state:
Methods:
Section titled “Methods:”Properties:
Section titled “Properties:”The ValidityState Object
Section titled “The ValidityState Object”The validity property of an input element returns a ValidityState object. This object has several boolean properties indicating why an element might be invalid:
JavaScript Validation Examples
Section titled “JavaScript Validation Examples”Example 1: Checking validity and displaying validationMessage
<input id="myNumberInput" type="number" min="100" max="300" required><button id="checkButton">Check Validity</button><p id="messageArea"></p>
<script> const numberInput = document.getElementById('myNumberInput'); const checkButton = document.getElementById('checkButton'); const messageArea = document.getElementById('messageArea');
checkButton.addEventListener('click', function() { if (numberInput.checkValidity()) { messageArea.textContent = 'Input is valid!'; messageArea.style.color = 'green'; } else { messageArea.textContent = numberInput.validationMessage; messageArea.style.color = 'red'; } });</script>Example 2: Using ValidityState properties for specific feedback
<input id="ageInput" type="number" min="18" max="99"><button id="checkAgeButton">Check Age</button><p id="ageMessage"></p>
<script> const ageInput = document.getElementById('ageInput'); const checkAgeButton = document.getElementById('checkAgeButton'); const ageMessage = document.getElementById('ageMessage');
checkAgeButton.addEventListener('click', function() { let message = ''; ageInput.checkValidity(); // Important to update validity state properties
if (ageInput.validity.rangeUnderflow) { message = 'Value too small. Minimum age is 18.'; } else if (ageInput.validity.rangeOverflow) { message = 'Value too large. Maximum age is 99.'; } else if (ageInput.validity.valueMissing) { message = 'Age is required.'; } else if (ageInput.validity.valid) { message = 'Age is valid.'; ageMessage.style.color = 'green'; } else { message = 'Invalid input.'; // Generic fallback } ageMessage.textContent = message; if (!ageInput.validity.valid) { ageMessage.style.color = 'red'; } });</script>Example 3: Custom validation messages with setCustomValidity()
<form id="signupForm"> <label for="username">Username (min 5 chars):</label> <input type="text" id="username" name="username" required minlength="5"> <button type="submit">Sign Up</button></form>
<script> const signupForm = document.getElementById('signupForm'); const usernameInput = document.getElementById('username');
usernameInput.addEventListener('input', function() { // Clear custom validity message on each input to allow native validation to re-evaluate usernameInput.setCustomValidity(''); if (usernameInput.validity.tooShort) { usernameInput.setCustomValidity('Username is too short! Please use at least 5 characters.'); } else if (usernameInput.value.toLowerCase() === 'admin') { usernameInput.setCustomValidity('"admin" is not a permitted username.'); } // Optional: report validity immediately on input // usernameInput.reportValidity(); });
signupForm.addEventListener('submit', function(event) { if (!signupForm.checkValidity()) { event.preventDefault(); // Prevent form submission if invalid // Browsers usually show validation messages on submit attempt // You could add further custom logic here if needed console.log('Form is invalid. Please correct errors.'); } });</script>Important Considerations
Section titled “Important Considerations”- Client-Side vs. Server-Side Validation: Client-side validation (like this API) improves user experience by providing immediate feedback. However, it is not a security measure. Malicious users can bypass client-side validation. Always implement robust validation on the server-side as well.
- Styling Invalid Fields: CSS pseudo-classes like
:valid,:invalid,:required,:optionalcan be used to style form elements based on their validation state. - Accessibility: Ensure that validation messages are accessible to users with disabilities (e.g., by associating error messages with form fields using
aria-describedby).
The Constraint Validation API provides a powerful baseline for form validation. For more complex scenarios or highly customized UI, you might combine it with custom JavaScript logic or use dedicated form validation libraries.