0

My regex works fine on regex101 and my regex is

[1-4]|(0)

But when I tried it on HTML input element's attribute it doesn't work as expected. My HTML is like below

<form action="/">
     <input type="text" id="usernum" name="usernum" pattern="[1-4]|(0)" title="1-4 and must include at leat one 0">
     <input type="submit">
</form>

I want users must enter one 0 along with the ranges digit.

4
  • | is for alternatives. So that matches either 1 through 4 or 0. It's the same as [0-4]. Commented Jun 17, 2020 at 5:28
  • If i use [0-4] user can skip 0 but I want to force them to enter at least one 0 Commented Jun 17, 2020 at 5:31
  • I know. I'm just explaining what your code does. Why did you think |0 would force a 0? Commented Jun 17, 2020 at 5:36
  • Perhaps ^(?=.*0)[0-4]+$ Commented Jun 17, 2020 at 5:36

1 Answer 1

1

The pattern attribute has to match the entire input.

([1-4]+0[0-4]*|[0-4]*0[1-4]+)+

The first alternative requires at least one digit 1-4 before a 0, the second requires at least one digit 1-4 after a 0. Then repeat it with + to allow more than one 0.

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.