- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - Forms API
Web Forms API
JavaScript Forms API is a web API that allows us to interact with and manipulate HTML forms. It provides a set of methods and properties that are used to perform client-side form validation. It’s also helpful to ensure data integrity before form submission. The forms API also referred to as Form Validation API or Constraint Validation API.
Here, we will discuss how to use various methods and properties to validate the form data using JavaScript.
Constraint Validation DOM Methods
In JavaScript, the constraint validation DOM method validates the input value by referencing the input fields. It validates the input value based on the HTML attributes you have used with the input.
After validating the input value, it returns a boolean value, representing whether the input value is valid.
Here is the list of the constraint validation methods.
Method | Description |
---|---|
checkValidity() | It returns a boolean value based on whether the input element contains a valid value. |
setCustomValidity() | It is used to set the custom message to the validationMessage property. |
Syntax
We can follow the syntax below to use the form validation methods.
element.checkValidity() OR element.setCustomValidity(message);
In the above syntax, you need to access the element using the selector and take it as a reference of the checkValidity() or setCustomValidity() method. The setCustomValidity() method takes the string message as an argument.
Example: Using the checkValidity() method
We created the number input in the code below and set 10 to the min attribute.
In the validateInput() function, we access the number input using the id and use the checkValidity() to validate the value of the number input.
If checkValidity() method returns false, we print the validation message. Otherwise, we print the numeric value.
<html> <body> <input type = "number" min = "10" id = "num" required> <p id = "output"> </p> <button onclick = "validateInput()"> Validate Number </button> <script> const output = document.getElementById("output"); function validateInput() { let num = document.getElementById("num"); if (num.checkValidity() == false) { output.innerHTML = "Please enter a number greater than 10"; } else { output.innerHTML = "Your number is " + num.value; } } </script> </body> </html>
Example: Using the setCustomValidity() Method
In the below code, we have defined the number input to take the user’s age in the input.
In the validateAge() function, we access the age input using its id and perform the custom validation on the input value. Based on the validation, we use the setCustomValidity() to set the custom validation message.
At last, we use the reportValidity() method to show the validation message set using the setCustomValidity() method.
You can enter the age below 18, and observe the validation message.
<html> <body> <form> <label> Enter your age: </label> <input type = "number" id = "age" required> <br> <br> <button type = "button" onclick = "validateAge()"> Validate Age </button> </form> <div id = "message"> </div> <script> function validateAge() { const ageInp = document.getElementById("age"); const output = document.getElementById("message"); const age = parseInt(ageInp.value); if (isNaN(age)) { ageInp.setCustomValidity("Please enter a valid number."); } else if (age < 18) { ageInp.setCustomValidity("You must be at least 18 years old."); } else { ageInp.setCustomValidity(""); // To remove custom error message output.innerHTML = "Age is valid!"; } ageInp.reportValidity(); // To display custom validation message } </script> </body> </html>
Constraint Validation DOM Properties
JavaScript also contains the DOM properties for constraint validation. It is used to check the particular validation of the input value.
Here, we have listed all DOM properties that can be used for the constraint validation.
Property | Description |
---|---|
validity | It contains multiple properties to perform the particular validation on the input element. |
validationMessage | It contains the validation message when the input element doesn't contain valid data. |
willValidate | It represents whether the input data will be validated. |
Properties of the 'validity' Property
In JavaScript, each element has the 'validity' property, containing multiple properties. You can use the particular property of the 'validation' property to perform the validation.
Here, we have listed all properties of the 'validity' property.
Property | Description |
---|---|
customError | It contains a true boolean value when you set the custom validity message. |
patternMismatch | When the parent element's value doesn't match the pattern, it sets true. |
rangeOverflow | It returns a boolean value based on whether the input value is greater than the max attribute's value. |
rangeUnderflow | It returns a boolean value based on whether the input value is less than the min attribute's value. |
stepMismatch | It returns a boolean value based on whether the step is mismatching in the numeric input. |
tooLong | If the length of the input element's value is greater than the maxLength attribute's value, it returns true. Otherwise, it returns false. |
typeMismatch | When the type of entered value doesn't match the 'type' attribute's value, it returns true. |
valueMissing | It returns a boolean value based on whether the input element is empty. |
valid | It returns true when the input element is valid. |
Syntax
Users can follow the syntax below to use the properties of the validation property.
element.validity.property;
You can use the different properties of the validity property of the element to validate the input element’s value.
Example
In the below code, we have defined the number input and set 300 for the value of the ‘max’ attribute.
In the validateNumber() function, we use the ‘rangeOverflow’ property of the ‘validity’ property of the input element to check whether the input value is greater than 300.
If the rangeOverflow property returns true, we print the ‘Number is too large’. Otherwise, we print the numeric value.
<html> <body> <form> <label> Enter Any Number: </label> <input type = "number" id = "num" max = "300" required> <br> <br> <button type = "button" onclick = "validateNumber()"> Validate Number </button> </form> <div id = "output"> </div> <script> const output = document.getElementById('output'); function validateNumber() { const numInput = document.getElementById('num'); if (numInput.validity.rangeOverflow) { output.innerHTML = "Number is too large"; } else { output.innerHTML = "Number is valid"; } } </script> </body> </html>
Example
In the below code, we have defined the text input.
In the validateText() function, we access the string input. After that, we used the ‘valueMissing’ property of the validity property to check whether the input value is empty.
In the output, you can keep the input value empty, click the validate text button and observe the error message.
<html> <body> <form> <label> Enter any text: </label> <input type = "text" id = "str" required> <br> <br> <button type = "button" onclick = "validateText()"> Validate Text </button> </form> <div id = "output"> </div> <script> const output = document.getElementById('output'); function validateText() { const strInput = document.getElementById('str'); if (strInput.validity.valueMissing) { output.innerHTML = "Please enter a value."; } else { output.innerHTML = "You have entered " + strInput.value + "."; } } </script> </body> </html>
You can also use the other properties of the ‘validity’ property to validate the form input data. If the data is not valid, you can show the custom error message using the setCustomValidity() method.