Demis Schroder Demis Schroder - 7 months ago 24
HTML Question

HTML Pattern numbers and optional - symbol

First question on this forum.
Im trying to make a HTML pattern that requiers numbers (length 1 to 20), and its optional to add a -.

so it should approve 040-123456 and 040123456.

Can anyone help me with this?

Answer

You can use this pattern:

(?=^\d*\-?\d*$)[\d\-]{1,20}

Explanation

  • (?=^\d*-?\d*$): Looks if the string is only composed by digits and one optional dash
  • [\d-]{1,20}: Looks for a string with only digits and dashes, from one to twenty characters