
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Regular Expression Validation to Input Element in HTML
The task we are going to perform in this article is about how to add a regular expression that an input elements value is checked against in HTML.
The regular expression that will be used to check the value of the input element is specified by the HTML <input> pattern attribute. The following input kinds are compatible with this attribute: text, password, date, search, email, etc.
Syntax
Following is the syntax for HTML <input>pattern attribute.
<input pattern = "regular_exp">
For getting more idea on how to add a regular expression that an input elements value is checked against in HTML, let's look into the following examples
For type= "password"
The type="password" attribute on the <input> tag creates a text field where users can safely enter a password. Depending on the browser, characters are replaced as they are entered by a dot ("?") or asterisk ("*").
Example
In the following example we are using the <input> element with type=" password".
<!DOCTYPE html> <html> <body> <form action="#"> <label for="tutorial">Password:</label> <input type="password" id="tutorial" name="tutorial" pattern=".{8,}" title="Eight or More Characters"> <input type="submit"> </form> </body> </html>
On executing the above script, it will generate the input field of type password with a pattern to make sure it will meet that limit to be submitted or else display an alert box.
For input field restricted with three letters
In thic case we are restricting the input field allowing the user to enter only three letters.
Example
Considering the following we are using the input field restricted with three letters with no numbers or special characters.
<!DOCTYPE html> <html> <body> <form action="#"> <label for="tutorial">Country Code:</label> <input type="text" id="tutorial" name="tutorial" pattern="[A-Za-z]{3}" title=" country code"><br><br> <input type="submit"> </form> </body> </html>
When the script gets executed, it will display an output with the name "countrycode" along with a submit button restricted only to three letters. If it doesn't match the limit it will display an alert box.