-1

我将使用获取正则表达式的参数执行一个函数,并使用它检查表单的字段。我有这个代码:

//The first function handler (no one runs):
field.onblur = function(){
    checkField(0, /^([a-z ñáéíóúü]{2,60})$/i, "name", "nameError", "Error in name");
}

//The function:
function checkField(numForm, regex, idField, idError, error){

    var form = document.getElementsByTagName("form")[numForm];
    var field = form.getElementById(idField);
    var spanError = form.getElementById(idError); 

    //Since here runs, so I think the problem is with the regex
    if(!regex.test(idField.value))
        spanError.innerHTML = error;
    else
        spanError.innerHTML = "";
}

制作函数并为其提供像参数一样的正则表达式的正确方法是什么?

4

1 回答 1

0

正则表达式通过正常,这两行是错误的:

var field = form.getElementById(idField);
var spanError = form.getElementById(idError);

getElementById()只是一种方法documentid您可以通过使用如下字符串来解决此问题:

var field = form[idField];
var spanError = form[idError];

...或使用getElementById()var field = document.getElementById(idField);

还有这一行(除非帖子中有错字)

if(!regex.test(idField.value))

应该:

if(!regex.test(field.value))
于 2013-11-12T05:12:21.923 回答