Reputation: 157
I am trying to make a pattern match a string that has the following rules:
Example Fails
Example Success
Edit for confusion:
This is for HTML Input Patterns
I have tried the following
((([A-Za-z]+[.][A-Za-z]+){1,15})([0-9]{0,2}))
But it does not stop at 15 characters
And this
([A-Za-z.]{1,15})([0-9]{0,2})
But it matches if there is no.
Upvotes: 1
Views: 579
Reputation: 607
You can use positive lookahead for this problem.
(?=.{1,15}$)([a-z]+\.[a-z]+[0-9]{0,2})
Taken from regular-expressions.info:
The difference is that lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.
The first part of this regular expression checks the length of your string, but - as stated above - no characters are consumed at all. So after that you can do your username checks you mentioned in your question.
Upvotes: 0
Reputation: 324810
Don't do it all at once.
First, breaking down a problem into smaller pieces is just good for maintaining it anyway.
Second, if you ever decide you want to change the requirements, you can do that much more easily.
Third, when a user submits a username, you can tell them exactly what about it you don't like. Specifying a single validation rule that fails is way better UX than just saying it's invalid.
So with all that said... HTML's pattern
attribute may not be the best method for validating such complex rules. Instead, you should use JavaScript to validate (and again on the server) and present custom validity text as needed.
input.onchange = function() {
if( this.value.length > 15) {
this.setCustomValidity("Max length: 15 characters");
return;
}
var parts = this.value.split(".");
if( parts.length != 2 || !parts[0] || !parts[1]) {
this.setCustomValidity("Must have two parts separated by a dot");
return;
}
if( this.value.replace(/\d+$/,'').match(/\d/)) {
this.setCustomValidity("Digits can only appear at the end");
return;
}
if( this.value.match(/\d{3}$/)) {
this.setCustomValidity("Max of two digits at the end");
return;
}
this.setCustomValidity(""); // valid
};
Upvotes: 1