Reputation: 19
I need to validate a string to have only letters, digits up to 4, '.', and '_';
Right now I am using
if(/^[a-zA-Z0-9_.]+$/.test(testString))
{
console.log("Valid string");
}
testString = test.com // (must be valid)
testString = Te_St.com // (must be valid)
testString = Te_St1.com // (must be valid)
testString = Te_St12.com // (must be invalid because has 12 in it and is higher than 4)
testString = Te_2St1.com // (must be valid)
testString = Te_24St1.com // (must be invalid because has 24 in it and it higher than 4)
testString = Te_2$St1.com // (must be invalid because has ilegal character $)
Upvotes: 0
Views: 45
Reputation: 67968
^(?!.*[1-9]\d)[a-zA-Z0-4_.]+$
Try this.See demo.
https://regex101.com/r/wU7sQ0/12
Upvotes: 1
Reputation: 89557
You can try the pattern below:
/^[a-z._]*(?:[01234](?:[a-z._]+|$))*$/i
but note that this pattern succeeds with an empty string. To prevent this, you can test the string length before or add a lookahead at the start of the pattern:
/^(?=.)[a-z._]*(?:[01234](?:[a-z._]+|$))*$/i
Upvotes: 2