JavaScript Forms
JavaScript Form Validation
You can use JavaScript to validate HTML forms.
If the first name field (fname) is blank, this function displays a warning message and returns false to stop the form submission:
JavaScript Example
function validateForm() {
let
x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
The action occurs when the form is submitted.
JavaScript Can Validate Numeric Input
JavaScript is commonly used to check if numeric input is valid.
Automatic HTML Form Validation
The browser can automatically perform validation for HTML forms.
If the first name field (fname) is left blank, the use of the required
attribute stops the form submission.
HTML form validation doesn't function automatically on Internet Explorer 9 or earlier versions.
Data Validation
Data validation is making sure that the information users provide is clean, accurate, and helpful.
Common validation tasks include:
- Did the person complete all the necessary fields?
- Did the user input a correct date?
- Did the user input numbers in a numeric field?
Data validation is typically done to make sure that the information entered by users is accurate.
Validation can mean checking in various ways and using different methods. It can be implemented in various ways.
The web server checks the input sent to it for errors through a process called Server-side validation.
Web browsers perform client-side validation before sending input to a web server.
HTML Constraint Validation
HTML5 brought in a fresh idea for HTML validation known as constraint validation.
HTML constraint validation relies on:
- Validation Limits for HTML Input Attributes
- Styling Constraints with CSS Pseudo Selectors
- Working with Constraints: DOM Properties and Methods
Constraint Validation HTML Input Attributes
Attribute | Description |
---|---|
disabled | Indicates that the input field should be inactive or not usable. |
max | Defines the highest possible value for an input element. |
min | Defines the smallest acceptable value for an input element. |
pattern | Defines the pattern for the value of an input field. |
required | Indicates that the input box needs an element. |
type | Describes the kind of an input element. |
Constraint Validation CSS Pseudo Selectors
Selector | Description |
---|---|
:disabled | Chooses input elements that have the "disabled" attribute set. |
:invalid | Chooses input elements that have incorrect values. |
:optional | Choose input elements that do not have the 'required' attribute specified. |
:required | Chooses input items that have the "required" feature specified. |
:valid | Choose input elements with correct values. |