0

Attempting to use a regex pattern for an HTML input element that limits the characters to 0-9, ",","-",".","$"

I have very little experience in regex and used the pattern=[0-9,.-$] on the input element and it does not work. Though I plan on studying regex intensely in the future, I need a little help on this for now. Thank you.

<form>
  <input name="currency" pattern=[0-9,.-$]>
  <button>Submit</button>
</form>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Elcid_91
  • 1,571
  • 4
  • 24
  • 50

2 Answers2

0

don't use regex, use native type="number" that will do job for you with no need for regex

coverage is almost full > https://caniuse.com/#feat=input-number

<form>
  <input type="number" name="currency">
  <button>Submit</button>
</form>
Kresimir Pendic
  • 3,597
  • 1
  • 21
  • 28
0

You have two problems.

  • - indicates a range, you already used it as such for 0-9. .-$ isn't a valid range. A validator would have highlighted this for you. You need to escape the -.
  • You are only matching one character. You need to match multiple so use something like + to mean one or more

<form>
  <input name="currency" pattern="[0-9,.\-$]+">
  <button>Submit</button>
</form>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I just ran you snippet and was able to type anything I wanted in the field. – Elcid_91 Aug 10 '20 at 14:26
  • @Elcid_91 — The `pattern` attribute doesn't prevent people from typing what they like. It prevents form submission when the value doesn't match. That's why I added the form and the submit button. – Quentin Aug 10 '20 at 14:28