Require both letters and numbers - regExp
I am trying to figure out how to require letters and numbers only without any other characters. So literally [a-z]
and / \d
or [0-9]
whichever is best for the numbers.
So, if I have a line that needs validation:
$toValidate = 'Q23AS9D0APQQ2'; // It may start with letter or number, both cases possible.
And then if I had a check for it:
return /([a-z].*[0-9])|([0-9].*[a-z])/i.test($toValidate);
I used a flag i
because it could be the user who enters it in lowercase or uppercase, that is the user's preference ... So the regex fails ... It accepts special characters as well, so this is an unwanted effect.
When checked above, this also passes:
$toValidate = 'asdas12312...1231@asda___213-1';
Then I tried something crazy and I don't even know what I did, so if anyone can tell me near the correct answer, I would really appreciate it.
return /([a-z].*\d)+$|(\d.*[a-z])+$/i.test($toValidate);
It seemed to be great. But then when I tried to continue typing letters or numbers after the special character, it still checks as true
.
Example:
$toValidate = 'q2IasK231@!@!#_+123';
So please help me understand better regularExpressions
and tell me how to validate the line at the beginning of my question. The letters and numbers expected in the string.
source to share
To allow only letters and numbers with at least one letter and at least one number:
/^(?=.*?\d)(?=.*?[a-zA-Z])[a-zA-Z\d]+$/
Regular Expression Distribution:
^ # start of input
(?=.*?\d) # lookahead to make sure at least one digit is there
(?=.*?[a-zA-Z]) # lookahead to make sure at least one letter is there
[a-zA-Z\d]+ # regex to match 1 or more of digit or letters
$ # end of input
You shouldn't use .*
in your regex, otherwise it will allow any character in the input.
source to share
what you are looking for in pseudo: START-ANCOR [a-zA-Z0-9] 0-> Inf times, ([a-zA-Z] [0-9] OR [0-9] [a-zA- Z]), [a-zA -Z0-9] 0-> Inf times END-ANCOR
in words, start with something from your lang, end with something from your lang, and join a seam between letters and numbers, or vice versa.
It should be like this:
/^([a-z0-9]* (([a-z][0-9]) | ([0-9][a-z])) [a-z0-9]*)$/i.
source to share
More than one type of character can be combined in brackets. So the following regex should work:
/ ^ ([a-z0-9] +) $ / i.
The ^ and $ match the beginning and end of the line, so the whole line will be checked for conditions. [A-z0-9] allows only letters and numbers to be matched. The + character matches one or more characters. And the "i" at the end, as you know, makes the case insensitive.
source to share