Does regex in HTML5 prevent spaces?

I have a regex for two different fields. Both will evaluate to correct values, but neither will allow the user to enter spaces. For example, in the Gender field, the user can simply enter a space and submit the form. I want to prevent the user from entering a space. Here is my regex:

Gender pattern="*[MmFf]?*"  #This field should allow M or F letter lower or upper case. Nothing else should be allowed. This field is 1 character only.

Grade pattern=" *(0?[0-9]|1[0-2]|[A-Z]{1,2})? *" #This should allow 01 or 1 and something like this PK or pk. No white space.

      

I'm not sure how to prevent whitespace in HTML5 template. if anyone knows how to fix this problem please let me know. Thank.

+3


source to share


1 answer


Your templates allow spaces ( *

) or blank lines. Make the patterns match at least something:

  • Floor: pattern="[MmFf]"

  • Rating: pattern="0?[0-9]|1[0-2]|[A-Za-z]{1,2}"

Remember that HTML5 templates do not require explicit bindings ^

and $

(unless some unusual frameworks override HTML5 behavior pattern

).



So, the first pattern is transferred to the template ^(?:[MmFf])$

and will only match line equal to M

, M

, F

or F

.

The second will be translated to ^(?:0?[0-9]|1[0-2]|[A-Za-z]{1,2})$

and will match the string (requiring full string matching)

  • 0?[0-9]

    - optional 0

    with a number
  • |

    - or
  • 1[0-2]

    - 10

    , 11

    or12

  • |

    - or
  • [A-Za-z]{1,2}

    - 1 or 2 ASCII letters upper or lower case
+1


source







All Articles