HTML5 introduces support for input validation. You manage input validation through attributes.
The following list shows which elements and input types support the different validation attributes.
The simplest kind of input validation is to ensure that the user provides a value. You do this with the required attribute.
The user cannot submit the form until a value has been provided.
<!DOCTYPE HTML> <html> <body> <form method="post" action=""> <p> <label for="name"> Name: <input type="text" required id="name" name="name"> </label> </p> <p> <label for="password"> Password: <input type="password" required placeholder="Min 6 characters" id="password" name="password"> </label> </p> <p> <label for="accept"> <input type="checkbox" required id="accept" name="accept"> Accept Terms & Conditions </label> </p> <input type="submit" value="Submit"> </form> </body> </html>
You use the min and max attributes to ensure that numeric and date values are within a specific range.
You need not apply both attributes.
The min and max values are inclusive, meaning that if you specify a max value of 100, then any value up to and including 100 is allowed.
<!DOCTYPE HTML> <html> <body> <form method="post" action=""> <p> <label for="price"> Rs. per unit in your area: <input type="number" min="0" max="100" value="1" id="price" name="price"> </label> </p> <input type="submit" value="Submit"> </form> </body> </html>
The pattern attribute ensures that a value matches a regular expression.
<!DOCTYPE HTML> <html> <body> <form method="post" action=""> <p> <label for="name"> Name: <input type="text" id="name" name="name" pattern="^.* .*$" /> </label> </p> </form> </body> </html>
The pattern ensures that the user enters two names, separated by a space.
The email and url types of the input element ensure that the user has entered a valid e-mail address or fully qualified URL, respectively.
We can combine the pattern attribute with these types to restrict the values, for example, limiting e-mail address to a particular domain.
<!DOCTYPE HTML> <html> <body> <form method="post" action=""> <p> <label for="email"> Email: <input type="email" placeholder="enter your email" required pattern=".*@mydomain.com" id="email" name="email" /> </label> </p> <input type="submit" value="Submit"> </form> </body> </html>
You can disable the form validation either by applying the novalidate attribute to the form element, or the formnovalidate attribute to the types of the button and input elements that can submit forms.
<!DOCTYPE HTML> <html> <body> <form method="post" action=""> <p> <label for="email"> Email: <input type="email" placeholder="Enter Your Email" required pattern=".*@mydomain.com" id="email" name="email"> </label> </p> <input type="submit" value="Submit"> <input type="submit" value="Save" formnovalidate /> </form> </body> </html>