在Javascript中仅验证a-z和A-Z字符

时间:2015-10-25 15:42:16

标签: javascript regex

我想让我的javascript文件验证输入“name”。我有一个允许字符设置为/^[A-Za-z]+$/的正则表达式。

但是,每当函数验证字符时,它都不会显示任何内容。我一直在关注示例here,但它仍然无效。这是我的代码:

function validateForm(){
   message = validateName();
   window.alert(message);
}

function validateName(){
    name = document.forms["supportForm"]["name"].value;
    allowedChars = /^[A-Za-z]+$/;
    if(name.value.match(allowedChars))
    {
        error = "You're Cool!";
        alert(error);
    }
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

var name已经定义为document.forms["supportForm"]["name"].value;的值 然后使用name.value,这没有任何意义。当您尝试在变量中获取子值时。相反,你想要name.match(allowedChars) 另外,我建议您使用console.log来测试输入错误修正。

function validateForm(){
   message = validateName();
   window.alert(message);
}

function validateName() {
    name = document.forms["supportForm"]["name"].value;
    console.log(name); //So you know it's picking up the value
    allowedChars = /^[A-Za-z]+$/;
    if(name.match(allowedChars)) {
        error = "You're Cool!";
        alert(error);
    }
}

答案 1 :(得分:0)

当引用已经引用了属性的变量时,您不需要再次引用该属性。

valuedocument.forms["supportForm"]["name"].value;

中引用了属性if(name.value.match(allowedChars))

处理此问题的正确方法是:

function validateForm(){
   message = validateName();
   window.alert(message);
}

function validateName(){
    name = document.forms["supportForm"]["name"].value;
    allowedChars = /^[A-Za-z]+$/;
    if(name.match(allowedChars))
    {
        error = "You're Cool!";
        alert(error);
    }
}
相关问题