Form Validation using JavaScript at Client Side - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Form Validation using JavaScript at Client Side

Share This

In a website, during form submission, the values of the form fields are sent to the web server. In some cases, the request submission of the form needs to be restricted until the mandatory fields are filled with valid data (data in the expected format), such as a login form must be filled with the user name and password (in the required format), a registration field should be filled with the user name, password, and re-type password, etc. If the form submission is not restricted, the data will be sent to the server from the client, which will generate an error. To restrict this submission, a client-side validation-related code can be implemented using JavaScript as per the requirement. It reduces network traffic as well as the load of the server.

The following example shows the form cannot be submitted if the input field is blank.

JavaScript Code

function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == "") { alert("Name must be filled out"); return false; } }

HTML Code

<form name="myForm" action="/another_page.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form>

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.