问题
I am using Jquery Validation.
Currently, I have a username, what i want to validate for this username is:
- Not blank
- Availability
- No whitespaces, I add this method: - $.validator.addMethod("nowhitespace", function(value, element) { return this.optional(element) || /^\S+$/i.test(value); }, " No white space please");
- Alphanumeric - $.validator.addMethod("alphanumeric", function(value, element) { return this.optional(element) || /^[a-zA-Z0-9]+$/i.test(value); }, " Alphanumeric. Only numbers and alphabet allowed");
- First characters must be alphabet, cannot be numeric. 
I am stuck at the last validation. How to write a regular expression to validate first character MUST be alphabet?
BTW:
The no whitespace seems having problem. I tried my script, 1 whitespace its allowed, but 2 whitespaces not allowed, why?
回答1:
Use
/^[A-Za-z][A-Za-z0-9]+$/
for the alphanumeric method.
This matches any string which consists of a letter followed by one or more alphanumeric characters. This assumes that single character user names are not allowed. If you do want to allow single character user names, change the pattern to:
/^[A-Za-z][A-Za-z0-9]*$/
This way, there is no need for a separate check for the first character. Incidentally, this should also obviate the need for the whitespace check as a string that consists entirely of alphanumeric characters cannot contain any whitespace by definition.
回答2:
value.substr(0, 1).match(/[A-Za-z]/) != null
来源:https://stackoverflow.com/questions/1303746/how-can-i-verify-that-user-name-starts-with-a-letter-and-contains-only-alphanume