How can I verify that user name starts with a letter and contains only alphanumeric characters?

只愿长相守 提交于 2020-01-03 02:51:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!