Core Concept of HTML Form Validation Example
To check the user data at the browser level before sending it to the server, this is known as client-side validation or validation on the front end.
In this code:
- A JavaScript method validateForm() is defined and executed before form submission.
- This method checks whether the name field is empty or not using document.forms[“myForm”][“fname”].value.
- If the field is empty, then it shows an error as a Windows alert and returns false that means form will not be submitted. So, the user can enter/fill in the name and press the submit button again.
Why is it used?
- To prevent sending wrong data, incomplete, or empty data to the server.
- To show the user an error to fill out the form without reloading the page.
Real-life Applications
- Sign-up & Login Forms: To ensure the username, password, and email are not empty.
- Checkout and Payment Forms: To check the mandatory fields or credit card details like card number, expiry date, CSV, etc.
- There are endless real applications of form validations, but we added only these two validations.
Key Benefits of this Program
- Save server load: The wrong data is not sent to the server, so the processing of wrong data is also removed.
- Instant user error feedback: If the user enters the wrong data, then the user can receive the error message instantly on the screen.
Limitations of this Program
- Space Problem: Users can add extra or unnecessary spaces to text-based fields, so you need to add the trim() JavaScript method to each field.
- Security (Client-Side Limitations): There, validations can be turned off at the browser level by the end user. So, server-side validation is a must.
