Js Validation
## JavaScript Form Validation
HTML form validation can be performed using JavaScript.
The following example code checks if a form field (fname) has a value. If it does not, an alert message is displayed, and the form submission is prevented:
## JavaScript Example
function validateForm(){var x = document.forms.value; if(x == null || x == ""){alert("Name must be filled out."); return false; }}
The above JavaScript code can be called from HTML code:
## HTML Form Example
Name:
[Try it Yourself Β»](#)
* * *
## JavaScript Validate Numbers
JavaScript is often used to validate numbers in input fields:
Please enter a number between 1 and 10:
Submit
[Try it Yourself Β»](#)
* * *
## HTML Form Automatic Validation
HTML form validation can also be performed automatically by the browser.
If the form field (fname) is empty, the **required** attribute prevents the form from being submitted:
## Example
[Try it Yourself Β»](#)
> Internet Explorer 9 and earlier versions do not support automatic form validation.
* * *
## Data Validation
Data validation is used to ensure that user input data is valid.
Typical data validation tasks are:
* Has the required field been filled in?
* Has the user entered valid data?
* Has the user entered text in a numeric field?
In most cases, data validation is used to ensure that the user has entered data correctly.
Data validation can be defined in different ways and invoked in multiple ways.
**Server-side validation** is performed after the data is submitted to the server.
**Client-side validation** is performed in the browser before the data is sent to the server.
* * *
## HTML Constraint Validation
HTML5 introduced a new way to validate HTML forms: constraint validation.
Constraint validation is an algorithm used by the browser to perform validation when a form is submitted.
HTML constraint validation is based on:
* **HTML Input Attributes**
* **CSS Pseudo-class Selectors**
* **DOM Properties and Methods**
### Constraint Validation HTML Input Attributes
| Attribute | Description |
| --- | --- |
| disabled | Specifies that the input element should be disabled |
| max | Specifies the maximum value for the input element |
| min | Specifies the minimum value for the input element |
| pattern | Specifies the pattern for the input element's value |
| required | Specifies that the input field is required |
| type | Specifies the type of the input element |
For a complete list, please see (#).
### Constraint Validation CSS Pseudo-class Selectors
| Selector | Description |
| --- | --- |
| :disabled | Selects input elements with the "disabled" attribute |
| :invalid | Selects invalid input elements |
| :optional | Selects input elements without the "optional" attribute |
| :required | Selects input elements with the "required" attribute |
| :valid | Selects input elements with valid values |
For a complete list, please see (#).
[](#)(#)
YouTip