views:

447

answers:

2

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?

A: 
value.substr(0, 1).match(/[A-Za-z]/) != null
ChaosPandion
I am testing your code. Brb :)
Um.. Is that jquery or just a normal javascript method?
This is all native JS.
ChaosPandion
+2  A: 

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.

(Thanks Funka).

Sinan Ünür
May I know why??
this answer beat mine out by a few seconds, with the exact same pattern. What it is doing is requiring a single char from [A-Za-z] and then requiring it to be followed by one or more chars from [A-Za-z0-9]. You could change the "+" to a "*" if you wanted to allow a username to be only one letter.
Funka
Works like magic. Thank you. Best answer!!
weird, cant choose your answer as the best answer. Is it something wrong with my browser?
@kanayaki First off, thank you for accepting my answer. You might want to wait a few minutes and try again.
Sinan Ünür
Sure, I will keep trying until it accepts. I am the one who should say "thank you", you solved the problem that I might take days to solve. Thanks :)))))