【问题标题】:Validate phone number by custom validator and javascript通过自定义验证器和 javascript 验证电话号码
【发布时间】:2011-07-01 10:09:29
【问题描述】:

我有一个 phoneTextBox 控件,其中包含 4 个 TextBox:

国家代码(1-3 位), 城市代码(1-7 位), 本地号码(1-7 位) 和额外的电话号码(1-5 位数)。

不需要额外的电话号码。

下面的代码不起作用。

    <script type="text/javascript">
    function ValidatePhoneNumber(source, args) 

    {
        if (     $('#<%=txtCountryCode.ClientID %>').val().match(/^\d{1,3}$) ||
                 $('#<%=txtCityCode.ClientID %>').val().match(/^\d{1,7}$) ||
                 $('#<%=txtMainPhoneNumber.ClientID %>').val().match(/^\d{1,7}$)
           )


        {
            if ($('#<%=txtExtraPhoneNumber.ClientID %>').val().length<=0)
            {
               args.IsValid = true;
               return;
            }
            else 
            {
                if ($('#<%=txtExtraPhoneNumber.ClientID %>').val().match(/^\d{1,5}$)
                {
                    args.IsValid = true;
                   return;

                }
                else 
                {
                    args.IsValid = false;

                }

            }
        }
        else 
                {
                    args.IsValid = false;

                }

}
</script>
    <div style="display: inline">
        <asp:CustomValidator runat="server" ForeColor="Red" ErrorMessage="Invalid format" ClientValidationFunction="ValidatePhoneNumber" />
        <div>
            <b>+</b><asp:TextBox ID="txtCountryCode" runat="server" Width="30px" MaxLength="3"></asp:TextBox>
            <asp:TextBox ID="txtCityCode" runat="server" Width="60px" MaxLength="7"></asp:TextBox>
            <asp:TextBox ID="txtMainPhoneNumber" runat="server" Width="60px" MaxLength="7"></asp:TextBox>
            <asp:TextBox ID="txtExtraPhoneNumber" runat="server" Width="50px" MaxLength="5"></asp:TextBox>
        </div>
    </div>

【问题讨论】:

  • 您使用了错误的选择器。试试这个:$("#").并且在正则表达式中也有遗漏的闭合斜线。
  • 是的。你说的对。但错误是“Uncaught SyntaxError: Invalid regular expression: missing /”

标签: javascript jquery asp.net regex validation


【解决方案1】:
    args.IsValid = $('#<%=txtCountryCode.ClientID %>').val().match(/^\d{1,3}$/) &&
                 $('#<%=txtCityCode.ClientID %>').val().match(/^\d{1,7}$/) &&
                 $('#<%=txtMainPhoneNumber.ClientID %>').val().match(/^\d{1,7}$/) &&
$('#<%=txtExtraPhoneNumber.ClientID %>').val().match(/^\d{0,5}$/);

【讨论】:

    【解决方案2】:

    您缺少以/ 结束所有正则表达式

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 2014-11-30
      相关资源
      最近更新 更多