Reputation: 691
This expression must adhere to specific rules:
1.- Between 2 and 8 characters total.
2.- Start with uppercase.
3.- Contain both lowercase and digits.
The first and second should be easy, but I can't get the third one to work.
This is the expression I came up with
([A-Z]+[A-Za-z0-9]*){2,8}
But it returns incorrect responses. Regular expressions are far from my forte, and this is the first time I had to use them outside of class.
This is my code, if it helps
var expresion = /([A-Z]+[A-Za-z0-9]*){2,8}/;
var re = new RegExp(expresion);
var t = $('#code').val();
if (re.test(t)) {
console.log(t+' works');
} else {
console.log(t+' not working');
}
Upvotes: 0
Views: 48
Reputation: 198324
This should fit your literal requirements (however, as comments state, they don't really make sense):
^(?=.{2,8}$)(?=.*[0-9])(?=.*[a-z])[A-Z][a-zA-Z0-9]*$
First, you need to anchor your match with ^
(start of string) and $
; otherwise you can just be picking up a matching substring, which will mess up your requirements.
Second, we use lookahead to validate several individual points: the string contains between 2 and 8 characters before it ends, the string contains a digit.
Third, we use the character classes to validate that it starts with an uppercase, and continues with a mix of uppercase, lowercase and digits.
EDIT: Forgot the lowercase requirement, thanks nnnnnn. And you are right, your version is better.
Upvotes: 1
Reputation: 103744
Use look aheads that comport to each condition:
/^(?=[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{2,8}$)(.*)/m
(As stated in comments, your target pattern is a minimum of 3 characters with the other conditions...)
Upvotes: 1