Javascript:在函数内调用函数的问题

时间:2015-06-03 04:06:43

标签: javascript validation

我正在尝试清理这个spaghettified代码,我决定将方法分成单独的功能对象,然后在单个验证函数中调用它们。代码在第一个函数上正确运行并正确返回一个警告框。但是,当我修复第一个警报并重新提交表单时,第二个函数向我发出警报以修复某些内容,我点击“确定”并立即获得第三个函数的警报。显然我需要输入一些代码来阻止程序运行后我单击ok to第二个函数警报以便我可以解决问题,但是如何解决?

var checkboxes = document.getElementsByName('days');
var valid      = false;

function textFieldValid(){
    var textFieldsReq = document.getElementsByName('textFieldReq');
    for( var i=0;i<9;i++ ){
        if ( !textFieldsReq[i].value ){
            alert ( 'You need to fill in the required* text field!' );
            textFieldsReq[i].focus();
            return false;
        }
    }
};


function checkboxesValid(){
    for ( var i = 0;i<checkboxes.length;i++ ){
        if ( checkboxes[i].checked ) {
        valid = true;
        break;
        }
    }
    if ( !valid ) {
        alert( 'You need to select at least one day!' );
        checkboxes[0].focus();
        return false;
    }
}

function lodgeValid(){
    var lodging = document.getElementsByName('lodge');
    for( var i=0; i<lodging.length; i++ ){
        if( lodging[i].checked ){
            valid=true;
            break;
        }
    }
    if ( !valid ) {
        alert( 'You need to select at least one option!' );
        lodging[0].focus();
        return false;
    }
}


function validate(textFieldsReq){
    textFieldValid();
    checkboxesValid();
    lodgeValid();    
};

1 个答案:

答案 0 :(得分:2)

您需要从每个测试中返回true / false,然后

var checkboxes = document.getElementsByName('days');

function textFieldValid() {
    var textFieldsReq = document.getElementsByName('textFieldReq');
    for (var i = 0; i < 9; i++) {
        if (!textFieldsReq[i].value) {
            alert('You need to fill in the required* text field!');
            textFieldsReq[i].focus();
            return false;
        }
    }
    //if valid return true
    return true;
};


function checkboxesValid() {
    //create local variables
    var valid = false;
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked) {
            valid = true;
            break;
        }
    }
    if (!valid) {
        alert('You need to select at least one day!');
        checkboxes[0].focus();
        return false;
    }
    //if valid return true
    return valid;
}

function lodgeValid() {
    var lodging = document.getElementsByName('lodge'),
        valid = false;
    for (var i = 0; i < lodging.length; i++) {
        if (lodging[i].checked) {
            valid = true;
            break;
        }
    }
    if (!valid) {
        alert('You need to select at least one option!');
        lodging[0].focus();
        return false;
    }
    //if valid return true
    return valid;
}


function validate(textFieldsReq) {
    //check whether all the tests are turnig true
    return textFieldValid() && checkboxesValid() && lodgeValid();
};