表格字段验证不起作用

时间:2011-02-25 18:08:34

标签: javascript forms variables verification

我有一些表单验证码似乎无法正常工作,我无法弄清楚原因。

function isTextFieldEmpty(textField){
    //return true or false depending on whether or not there is any text in the field

        console.log("Checking to see if the current field is empty...");

    var val = textField.value;          //val is the text from the current field
        console.log("The current value of 'val' is: " + val);
    if(val.length < 1){
        return true;
    }else{
        return false;
    }

}

我得到的错误是:“Uncaught TypeError:无法读取未定义的属性'长度'。果然,我的控制台日志说'val'的值是 undefined

我确定我错过了一些东西,但我还在学习JS并且无法弄清楚它是什么。有什么建议吗?


编辑:这是我传递给函数的内容:

var uName = document.getElementById("unionname");
var noUnionName = isTextFieldEmpty(uName);

'unionname'是我正在尝试验证的texfield的id。这是相关的HTML:

    <div class="formBox">
        <label for="unionname">Union Name</label>
        <input type="text" name="unionname" id="unionname" value="" class="wide"/>
        <span class="feedback good">Sample good message</span>
    </div>

2 个答案:

答案 0 :(得分:0)

您在该功能中本地声明var val。尝试通过将其置于脚本的顶部来全局声明它;不需要设置它,只需声明它。

答案 1 :(得分:0)

我已经开始工作了。似乎验证功能很好;问题出在我的称呼方式上。

window.onload = justDoIt;

function justDoIt() {

    var uName = document.getElementById("unionname");

    uName.onblur = function(){
        clearMessages(uName);       // clear out old feedback for this field

        var noUnionName = isTextFieldEmpty(uName);

这就是我最终调用该函数的方式。


具有讽刺意味的是,似乎我从前一个例子中遗漏的错误的.onblur代码可能是我的问题的原因。但我真的不确定。

相关问题