Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  109] [ 1]  / answers: 1 / hits: 18609  / 15 Years ago, thu, august 20, 2009, 12:00:00

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?


More From » regex

 Answers
263

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.


[#98873] Sunday, August 16, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliotristinv

Total Points: 181
Total Questions: 99
Total Answers: 96

Location: Argentina
Member since Fri, Oct 21, 2022
2 Years ago
;