Thursday, August 11, 2016

JavaScript Form Validation


HTML form validation can be done by a JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:

JavaScript Example

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
The function can be called when the form is submitted:

HTML Form Example

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

JavaScript Can Validate Numeric Input

JavaScript is often used to validate numeric input:
Please input a number between 1 and 10

Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being submitted:

HTML Form Example

<form action="demo_form.asp" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>
Automatic HTML form validation does not work in Internet Explorer 9 or earlier.

Data Validation

Data validation is the process of ensuring that computer input is clean, correct, and useful.
Typical validation tasks are:
  • has the user filled in all required fields?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct input to a computer application.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.

No comments:

Post a Comment