如何验证用户名是否以字母开头并且仅包含字母数字字符? [英] How can I verify that user name starts with a letter and contains only alphanumeric characters?

查看:718
本文介绍了如何验证用户名是否以字母开头并且仅包含字母数字字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jquery验证

目前,我有一个用户名,我要为此用户名验证的是:

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:

    似乎没有空格有问题。我尝试了我的脚本,1允许空格,但不允许2个空格,为什么?

    The no whitespace seems having problem. I tried my script, 1 whitespace its allowed, but 2 whitespaces not allowed, why?

    推荐答案

    使用

    /^[A-Za-z][A-Za-z0-9]+$/
    

    字母数字方法。

    这匹配任何字符串由一个字母后跟一个或多个字母数字字符组成。这假定不允许使用单个字符的用户名。如果您确实想要允许单个字符用户名,请将模式更改为:

    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.

    这篇关于如何验证用户名是否以字母开头并且仅包含字母数字字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆