Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept more than 1 HTML5 pattern on an input?

I'm working on a form where I have to get book's ISB numbers. ISBN numbers can be 9 or 13 digits long and i would like to check the input with HTML5 pattern, but I've to accept 9 or 13 long numbers both.

How can I write it down with HTML5?

like image 971
cyrfandli Avatar asked Apr 01 '14 12:04

cyrfandli


People also ask

What does html5 pattern attribute do?

The pattern attribute specifies a regular expression the form control's value should match. If a non- null value doesn't conform to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true.

How do you input a pattern?

The pattern attribute specifies a regular expression that the <input> element's value is checked against on form submission. Note: The pattern attribute works with the following input types: text, date, search, url, tel, email, and password. Tip: Use the global title attribute to describe the pattern to help the user.

What is pattern validation?

Pattern validation is achieved using regular expressions, which is a string of characters and symbols that defines a search pattern. For example, let's say you have an Input element where you want users to enter a username.

How do I validate only alphabets in HTML?

You can write a JavaScript form validation script to check whether the required field(s) in the HTML form contains only letters. To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.


2 Answers

In the pattern attribute you can use regex:

<input type="text" pattern="\d{9}|\d{13}">

So this is not specific to HTML5, this is basic regex. | means alternatives.

  • The Regex explained
  • Demo
like image 93
kapa Avatar answered Oct 21 '22 13:10

kapa


The pattern attribute is based on regular expressions. RegEx {} checks for character occurences (in your case 9 and 13).

You can't check for exactly two different (non-adjacent) lengths with one expression and one {} notation.

You would need to write two expressions: the first one checks for 11 characters and the second one for 15 characters. You can chain these two regular expressions with some conditionality. Some If-else-conditionality exists, but may not be supported by the browsers.

Example: pattern="{9}|{13}"

like image 45
user3484917 Avatar answered Oct 21 '22 13:10

user3484917