vlovystack
vlovystack

Reputation: 703

Combining two regex in input restriction "pattern"

I need to have an input field where the user can only enter 7 numbers, nothing more, nothing less, nothing else.

I need (check for 7 characters)

pattern=".{7,7}"

and (check for only numbers)

pattern="\d*"

working together, but you can't define pattern two times, how would I combine these two together?

Upvotes: 2

Views: 416

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may use

pattern="\d{7}"

or with explicit anchors:

pattern="^\d{7}$"

See a regex demo.

You do not need to specify identical values for the minimum and maximum thresholds. In case you want to allow 1 to 7 digits, then it makes sense: pattern="\d{1,7}".

input:valid {
  color: black;
}
input:invalid {
  color: navy;
}
<form name="form1"> 
 <input type="text" pattern="\d{7}" title="7 digits only!" required/>
 <input type="Submit"/> 
</form>

To make the input field obligatory, add the required attribute.

Upvotes: 2

Mazai E S
Mazai E S

Reputation: 49

Try this code

 pattern="[0-9]{7}"

Upvotes: 0

Related Questions