What is the easiest way to check if an expression has English or number characters only? with no spaces and no other characters.
p.s - the first character cannot be a number. upper or lower case.
I would use: /^[A-Za-z][A-Za-z0-9]*$/
. Here are same examples:
/^[A-Za-z][A-Za-z0-9]*$/.test("expression");
/^[A-Za-z][A-Za-z0-9]*$/.test("EXPRESSION");
/^[A-Za-z][A-Za-z0-9]*$/.test("e123xpression");
/^[A-Za-z][A-Za-z0-9]*$/.test("E123xpression");
/^[A-Za-z][A-Za-z0-9]*$/.test("1expression");
Without boundaries (^
and $
) regexp match any substring too.
EDIT: Updated invalid expression
Easiest:
/^[a-z][a-z0-9]*$/i
explanation of the expression:
/
- open expression^
- string must start here. Nothing before[a-z]
- find only one character between a to z, including[a-z0-9]*
- find any sequence of characters either between a to z including, or between 0-9 including (the "any sequence" part is the * in the end)$
- string must end here. Nothing after/
- close expressioni
- the expression is case insensitivetested with the following cases
var tests = //key = case, value = expected results
{ "joe" : true //only lower case
, "JOE" : true //only capital
, "charsAndCaps" : true //mixed case
, "ABC444" : true //caps and numbers
, "AAaaAA3276" : true //mixed case with numbers
, "111Joe" : false //starts with number
, "112345" : false //only numbers
, "asaaa$" : false //non-alphanumeric char in the end
, "asaaaלא" : false //non-latin char in the end
, "asaaнет" : false //non-latin char in the end
, "#asaaa" : false //non-alphanumeric char in the start
, "לאasaaa" : false //non-latin char in the start
, "нетasaa" : false //non-latin char in the start
, "aaלאasaa" : false //non-latin char in the middle
, "sssнетaa" : false //non-latin char in the middle
, "as&&aaa" : false //non-alphanumeric char in the middle
, "" : false //empty string
}
try it at: http://jsfiddle.net/erJ4H/161/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With