I need a regex that checks if there are more than two letters.
It should only allow one letter.
But allow numbers.
For example
- 1a is good
- 1ab is bad
- 11 is good
- 11ab is bad
I have one, it also takes as wrong when there are any numbers... I do want to allow numbers. Just not more than one letter.
This is my rgex:
export const onlyOneCharacter = (string) => {
return /^[A-Za-z]{0,1}$/.test(string) ? undefined : "wrong";
};
Returning undefined mean its correct, so it doesnt show any validation error.
CodePudding user response:
If there can be no two consecutive letters in the string, you can use
const texts = ["1a", "1ab", "11", "11ab"];
const onlyOneCharacter = (string) => {
return /[A-Za-z]{2}/.test(string) ? "wrong" : "correct";
};
console.log( texts.map(onlyOneCharacter) )
If you need to check for two letters that are not necessarily consecutive, you can use
const texts = ["1a", "1ab", "11", "11ab"];
const onlyOneCharacter = (string) => {
return /[A-Za-z][^A-Za-z]*[A-Za-z]/.test(string) ? "wrong" : "correct";
};
console.log( texts.map(onlyOneCharacter) )
Note that [A-Za-z][^A-Za-z]*[A-Za-z]
regex searches for a letter, then zero or more non-letter chars, and then a letter anywhere inside the string.
If the pattern is matched, the result is wrong
, else, the return value is correct
.
CodePudding user response:
I would use
^\d*[a-z]?\d*$
See the regex demo
JavaScript Example
const onlyOneCharacter = (string) => {
return /^\d*[a-z]?\d*$/.test(string) ? undefined : "wrong";
};
console.log(onlyOneCharacter("1a"));
console.log(onlyOneCharacter("1ab"));
console.log(onlyOneCharacter("11"));
console.log(onlyOneCharacter("11ab"));