I have a regex
/^([a-zA-Z0-9]+)$/
this just allows only alphanumerics but also if I insert only number(s) or only character(s) then also it accepts it. I want it to work like the field should accept only alphanumeric values but the value must contain at least both 1 character and 1 number.
And an idea with a negative check.
^(?!
at start look ahead if string does not\d*$
contain only digits|
or[a-z]*$
contain only letters[a-z\d]+$
matches one or more letters or digits until$
end.Have a look at this regex101 demo
(the
i
flag turns on caseless matching:a-z
matchesa-zA-Z
)This solution accepts at least 1 number and at least 1 character:
The accepted answers is not worked as it is not allow to enter special characters.
Its worked perfect for me.
^(?=.*[0-9])(?=.*[a-zA-Z])(?=\S+$).{6,20}$
Thank you.
I can see that other responders have given you a complete solution. Problem with regexes is that they can be difficult to maintain/understand.
An easier solution would be to retain your existing regex, then create two new regexes to test for your "at least one alphabetic" and "at least one numeric".
So, test for this :-
Then this :-
Then this :-
If your string passes all three regexes, you have the answer you need.
Maybe a bit late, but this is my RE:
/^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/
Explanation:
\w*
-> 0 or more alphanumeric digits, at the beginning\d+[a-zA-Z]|[a-zA-Z]+\d
-> a digit + a letter OR a letter + a digit\w*
-> 0 or more alphanumeric digits, againI hope it was understandable
Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead: