You Unknown
You Unknown

Reputation: 23

Pure HTML input type text validation using pattern

Recently I tried alot but I still unable to figure how should I able to validation for my text field. I hope I can get some help from here, my questions is I want to validate input text field only accept A-Z a-z 0-9 and space within word. And at least one char or number. For example, "abc def" , "abc092", "abcdef" Only in HTML input tag element . I tried this but this pattern unable to fullfil my requirements.

the pattern i want to achieve is

1) abc def 2) abcdef 3) abc123 4) a1b2c3 d4e5 5) allow to have empty space within words

the pattern i dont want to accept is

1) empty string 2) no alot of whitespace at the begining or end of the string 3) no bracket and etc special characters

Upvotes: 2

Views: 2285

Answers (3)

Jon P
Jon P

Reputation: 19772

Try

<input type="text" pattern="^\w+([\w ]*\w)*$">

Basically the break down is this:

\w+ - Select a word character ("A-z0-9") one or more times

()* - Select what's in here 0 or more times, which is

[\w ]*\w - Select a word character or space one or more times followed by another word character

No leading or trailing white space allowed. Only word characters allowed and internal spaces.

For some unit tests and breakdown of the regex see: https://regex101.com/r/7UnL9J/1

Upvotes: 1

Bara Ahmad
Bara Ahmad

Reputation: 21

Have you tried this?

<input type="text" pattern="[a-zA-Z0-9\s]+">

Upvotes: 0

Divakar
Divakar

Reputation: 76

You can use the Pattern attribute with regex but it is supported only in HTML 5. Like this " id="username" pattern="[A-Za-z0-9]+"

Check the below link for more information https://html.com/attributes/input-pattern/#Username_Patterns

Upvotes: 0

Related Questions