What is HTML5 Pattern?
The HTML5 pattern attribute is nothing but a JavaScript Regular Expression. It is used to match form field's value against the specified format. Patterns are used to validate email addresses, dates, credit card numbers, zip codes and so on.
For example, the following pattern requires one number and three uppercase character, if you didn't enter the said format it will prompt you with a message:
Similarly, if you have a field to accept only five numeric values, use this pattern:
pattern="\d{5}" in this pattern the '\d' stands for numeric values and '{5}' to accept only five characters.
Demo: http://jsfiddle.net/fhcox947/
Let's validate a DD/MM/YYYY date format:
Here's the pattern we need to use for validating this date format - pattern="(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/\d{4}"
The first section of this pattern (0[1-9]|[12][0-9]|3[01]) says - use 0 before the first value 1-9 except when the first value is 1/2, and use 0-9 after the first 1/2 value, and when the first values is 3 use only 0/1 after it. Sounds simple? I guess yes :)
Demo: http://jsfiddle.net/j8qpe3ca/
I hope you have understood how the patterns work—please refer this HTML5 pattern website for some common regular expression styles.
The HTML5 pattern attribute is nothing but a JavaScript Regular Expression. It is used to match form field's value against the specified format. Patterns are used to validate email addresses, dates, credit card numbers, zip codes and so on.
For example, the following pattern requires one number and three uppercase character, if you didn't enter the said format it will prompt you with a message:
pattern="[0-9][A-Z]{3}"Demo: http://jsfiddle.net/aoq22s54/
Similarly, if you have a field to accept only five numeric values, use this pattern:
pattern="\d{5}" in this pattern the '\d' stands for numeric values and '{5}' to accept only five characters.
Demo: http://jsfiddle.net/fhcox947/
Let's validate a DD/MM/YYYY date format:
Here's the pattern we need to use for validating this date format - pattern="(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/\d{4}"
The first section of this pattern (0[1-9]|[12][0-9]|3[01]) says - use 0 before the first value 1-9 except when the first value is 1/2, and use 0-9 after the first 1/2 value, and when the first values is 3 use only 0/1 after it. Sounds simple? I guess yes :)
Demo: http://jsfiddle.net/j8qpe3ca/
I hope you have understood how the patterns work—please refer this HTML5 pattern website for some common regular expression styles.