0

Consider the following set of codes:

<form>
  <label for="user_data">Input the angle:</label>
  <input type="text" id="user_data" name="user_data" pattern="[0-9][+]" title="Valid input required"><br><br>
  <input type="submit">
</form>

If the user inputs just any number, it's ok. But he inputs a + sign, then there must be something after the plus sign. But the above program doesn't work. I know that this type of questions have been answered earlier, but I just want to know if the pattern=[0-9][+] is valid so that the user is only allowed to input any number with a plus sign in it.

Edit: The input can never start with a + sign. Valid inputs can be 3+4 or only 3.

M.Riyan
  • 79
  • 5
  • Maybe `[0-9]+\+?[0-9]+`. Not really clear what the full regex scope should be. `33+` is valid, `3+33`, `33+33`? – user3783243 Jul 28 '23 at 14:13

1 Answers1

0

If you want a number with an optional leading plus sign, then use:

\+?[0-9]+

Or maybe:

^\+?[0-9]+$

if you prefer to have anchors

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Regarding "*if you prefer to have anchors*", they are already there when the regex is compiled. In Chrome, the `pattern="\+?[0-9]+"` results in a `/^(?:\+?[0-9]+)$/v` regex. No need to repeat anchors. – Wiktor Stribiżew Jul 28 '23 at 11:24
  • @Victor Thanks, and I largely expected this, but added it to my answer to be safe. – Tim Biegeleisen Jul 28 '23 at 11:25
  • @TimBiegeleisen But I do not want the input to be starting with + sign. The user can actually give two types of inputs: 3+4 or 3. Starting the input with a + sign is strictly prohibited. – M.Riyan Jul 28 '23 at 14:07
  • @M.Riyan You need to further update the question. `he inputs a + sign, then there must be something after the plus sign` is not true. – user3783243 Jul 28 '23 at 14:11