Table of Content
It’s crucial to confirm the form submitted by the consumer as it may have improper values.
JavaScript provides the facility to confirm the form on the client-side. Consequently, information processing will be quicker than regretting validation. The majority of internet programmers favor JavaScript form validation.
Why is JavaScript important for data validation?
With JavaScript, we could validate password, name, email, date, phone numbers, and much more data.
Email addresses must always have precisely the same structure: name@example.com An email form area should check whether the user has entered an email address correctly, and an extension. That is a lot to test.
An age-old question is: “where can we check for valid input: server-side or client-side?” Server-side checking involves the user submitting the form to the host, such as ASP, C# or PHP, then the host code assesses and returns an error when it finds you. It can be a lengthy and expensive trip. Client-side validation usually implies: JavaScript intercepting the kind before it is submitted to test for mistakes, maybe using regex.
It conserves the journey to the host but still employs a little bit of code. While we ought to even utilize server-side validation, we will discuss how we could take advantage of client-side validation to decrease the number of server requests.
How can we validate a form with JavaScript?
In this example, we are going to validate the name and password. The name can’t be empty, and the password can’t be less than six characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next page until given values are correct.
<script> function validateform(){ var name=document.myform.name.value; var password=document.myform.password.value; if (name==null || name==""){ alert("Name can't be blank"); return false; }else if(password.length<6){ alert("Password must be at least 6 characters long."); return false; } } </script> <body> <form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" > Name: <input type="text" name="name"><br/> Password: <input type="password" name="password"><br/> <input type="submit" value="register"> </form>