2

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

8
  • Please show exactly what you have tried. Preferably as a minimal reproducible example Commented Dec 16, 2019 at 6:07
  • Is there minimum string length? I.E. should "A" match Commented Dec 16, 2019 at 6:21
  • Helllo buddy why you deleted your Question about the JSON obj conversion!!?? Commented Feb 24, 2020 at 4:07
  • Open a new question i finished the code Commented Feb 24, 2020 at 4:11
  • hello...................... Commented Feb 24, 2020 at 5:55

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Have you tried this?

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

1 Comment

for this pattern pattern="[a-zA-Z0-9\s]+" <--- this allow empty whitespaces. how can i validate it if it's a empty whitespaces?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.