Javascript 姓名验证不起作用

标签 javascript validation

嘿伙计们,我想在 JavaScript 中验证姓名等。

var regex = /^[A-Za-z ]{1,20}$/;

当我输入 harun(这显然是 true)但它给出 false,当我输入 harun12 它也给出 false。谁能告诉我这段代码做错了什么?

函数检查() {

            var name = document.getElementById('<%= txt2.ClientID%>');
            var surname = document.getElementById('<%= txt3.ClientID%>');

            var textregex = /^[A-Za-z ]{1,20}$/;
            alert(textregex.test("harun"));

            if ((name.value == '') || (textregex.test(name) == false) ) {
                $("#name_error").dialog("open");
                $("#txt2").val('');

            }
            if ((surname.value == '') || (textregex.test(surname) == false){
                $("#surname_error").dialog("open");
                $("#txt3").val('');

            }


        }

    });

        <asp:TableRow ID="TableRow2" runat="server">
            <asp:TableCell>Name:</asp:TableCell><asp:TableCell>
                <asp:TextBox ID="txt2" runat="server" />
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txt2" />
            </asp:TableCell>
        </asp:TableRow>

        <asp:TableRow ID="TableRow3" runat="server">
            <asp:TableCell>Surname:</asp:TableCell><asp:TableCell>
                <asp:TextBox ID="txt3" runat="server"/>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txt3" />
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>

最佳答案

根据您的评论name指的是dom对象而不是它的值,所以使用

alert(textregex.test(name.value)); 
//                       --^--

var name = document.getElementById('<%= name.ClientID%>').value;
//                                                        --^--

更新

if ((name.value == '') || (textregex.test(name.value) == false)) {
  //                                           --^--
  $("#name_error").dialog("open");
  $("#txt2").val('');
}
if ((surname.value == '') || (textregex.test(surname.value) == false)) {
  //                                                 --^--
  $("#surname_error").dialog("open");
  $("#txt3").val('');
}

关于Javascript 姓名验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33038095/

相关文章:

javascript - 查找链接并使其可点击

javascript - 哪个 JavaScript 灯箱最像苹果网站上的灯箱? (提供链接)

javascript - 获取相关模型数据ember.js

javascript - 非数字正则表达式 + 仅允许单个 "."用于输入验证

javascript - 通过数组中的后续位置将字段添加到数组内的对象

javascript - 从 api 响应中获取特定值

javascript - 如何查找 HTML 表单中哪个子元素无效

c# - 我可以在自定义 ConfigurationSection 上使用 IntegerValidator 属性指定范围吗?

python - 如何在没有 try/except 或 str.isdigit 的情况下检查字符串是否包含数字?

c# - 在控件 C# 中获取 c.SelectedItem