Input validation in JavaScript for a web form can be performed using built-in HTML5 attributes, regular expressions (regex), and event handlers.
HTML5 provides attributes like ‘required’, ‘pattern’ and ‘maxlength’ that can validate simple inputs. For example, the ‘required’ attribute ensures an input field is filled before submission.
For complex validations, regex can be used. Regex allows pattern matching within the input data. It’s useful for validating email addresses or phone numbers. An invalid input can be detected by comparing it with a predefined pattern.
Event handlers such as ‘onsubmit’ for forms and ‘onchange’ for individual elements can trigger validation functions. These functions can contain custom logic to check user inputs. If the validation fails, you can prevent form submission using ‘event.preventDefault()’.
Here’s a code snippet:
document.getElementById("myForm").addEventListener("submit", function(event){
var x = document.forms["myForm"]["fname"].value;
alert("Name must be filled out");