I want to validate the input value using regex. The value should be string without white space at the beginning. But accept space in the middle. This value only accepts alphabets.
Example:
" abcde" -> not accepted
"abcdef lksfksl" -> accepted
"asma124" -> not accepted
"abcde" -> accepted
"abce,./()$#%"-> not accepted
I tried a couple of regEX.
/^[A-Za-z][A-Za-z-s]*$/
– When I want to delete all alphabets from input last one alphabet is not deleted. If my value is abcde
, then a
is not deleted when I clicked the delete button.
^[A-Za-zs]*$
– Empty string is accepted. " abcde" is accepted
/^[^s].+[a-zA-Z]+[a-zA-Z]+$/
– No alphabet is showing in my input field when I am typing.
I don’t understand how to achieve it.
4
Answers
Look for a string that starts with
a-z
, then either immediately ends or is followed by[a-zs]*[a-z]
. This ensures the last character is not whitespace.Note that if you pass the case-insensitive flag
/i
, you do not need to typea-zA-Z
.So first character is strictly letter, and others are letters or white space.
+ is like greedy character, you might want to switch it for *, but it seems to work as it is.
/^(w)[a-zA-Z ]+/gm.test(" abcde")
You could write a case insensitive pattern as:
Explanation
^
Start of string[a-z]+
Match 1+ chars a-z(?:[a-zs]*[a-z])?
Optionally match chars a-z or whitespace chars followed by a char a-z$
End of stringRegex demo
You can achieve this by using this
RegExp
:/^[a-zA-Z]+[a-zA-Zs]*?[^0-9]$/
Explanation :
^
Start of string[a-zA-Z]+
Matches 1 or more alphabets (Both Lower case and Upper case)[a-zA-Zs]*?
Optionally matches alphabets and whitespace character.[^0-9]
Will not accept the numeric values$
End of stringLive Demo :