Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 带嵌套测试的JQuery/AJAX表单验证…优雅的解决方案?_Javascript_Jquery_Ajax_Forms_Validation - Fatal编程技术网

Javascript 带嵌套测试的JQuery/AJAX表单验证…优雅的解决方案?

Javascript 带嵌套测试的JQuery/AJAX表单验证…优雅的解决方案?,javascript,jquery,ajax,forms,validation,Javascript,Jquery,Ajax,Forms,Validation,我正在使用JQuery/AJAX执行表单验证。当条目丢失或格式不正确时,我希望通过alert()发送消息,并将用户返回到表单,所有字段保持原样,以便用户可以编辑它们并再次尝试提交表单。我也不希望用户为每个格式错误的字段获取一系列alert()框,而是希望发现格式错误的第一个字段应该发出alert()框;单击alert()框后,用户可以返回编辑表单。如果有6个格式不正确的字段,我不希望一系列6个连续的alert()框,而是希望例程发现的第一个框出错并返回到表单(最终用户会使它们恢复正常) 我使用了

我正在使用JQuery/AJAX执行表单验证。当条目丢失或格式不正确时,我希望通过alert()发送消息,并将用户返回到表单,所有字段保持原样,以便用户可以编辑它们并再次尝试提交表单。我也不希望用户为每个格式错误的字段获取一系列alert()框,而是希望发现格式错误的第一个字段应该发出alert()框;单击alert()框后,用户可以返回编辑表单。如果有6个格式不正确的字段,我不希望一系列6个连续的alert()框,而是希望例程发现的第一个框出错并返回到表单(最终用户会使它们恢复正常)

我使用了一种有效的方法,尽管它不优雅,编辑起来也不繁琐,而且容易出错……它就像一系列俄罗斯玩偶,第一个错误阻止了后续例程的运行。当有5个字段或需要多种完整性检查的字段时,嵌套的IF-ELSE语句的数量会呈指数级增加,对于通过GET传递数据到PHP文件的表单,如下所示:

$.get('admin_email_length_check.php', { new_email: $('#new_email').val(), max_email_length: max_email_length }, function(data) {
    if (data != 0) {
        alert(data);
    } else {    
…它必须通过以下方式关闭:

    }
});
…不仅仅是一个简单的问题:

}
但这里有一个2字段验证的简短例程。我将allow_submit设置为FALSE并阻止提交,直到通过所有完整性检查,此时allow_submit变为TRUE,我动态重新提交表单;这意味着完整性检查(及其e.preventDefault();)将被完全绕过,然后表单将被处理。同样,它是有效的,但是我需要为具有许多字段的表单构造的IF-ELSE结构,这些字段需要多种类型的表单验证,需要使用经过仔细编辑的右大括号(或大括号+圆括号+;,等等)的非常长的结构。是否有一种更短或更优雅的方法可以做到这一点

var allow_submit = false;
$('#change_password_form').on('submit', function(e) {
    if (!allow_submit) {
        e.preventDefault();
        // First ensure that at least one of the fields has a value:
        if (($('#new_password').val() == '') && ($('#retype_password').val() == '')) {
            alert("Nothing specified in either of the 'Change Password' fields.\n\nAdd data and re-submit.\n");
        } else {
            // Ensure both fields are filled:
            if (($('#new_password').val() == '') || ($('#retype_password').val() == '')) {
                alert("When changing your password, both the 'New Password' and the 'Retype Password' fields must be filled.\n\nPlease supply new, matching passwords in both fields and re-submit.\n");
            } else {
                // Do the two fields match?
                if ($('#new_password').val() != $('#retype_password').val()) {
                    alert("New Password fields do not match.\n\nPlease edit password fields and re-submit.\n");
                 } else {
                    allow_submit = true;
                    $('#change_password_form').submit();
                 }
            }
        }   
    }
});

我有两个建议:

  • 使用早期的
    return
    语句稍微取消嵌套代码
  • 如果条件逻辑太多,请尝试使用数据结构 以下是我的尝试:

    $('#change_password_form').on('submit', function(e) {
        var data = collect_data();
        if (!data_is_valid(data)) {
            e.preventDefault();
        } else {
            // Submit.
        }
    });
    
    function collect_data() {
        return {
            passwords {
                new_: $('#new_password').val(),
                retyped: $('#retype_password').val()
            },
            ...
        };
    }
    
    function data_is_valid(data) {
        if (!password_is_valid(data.passwords)) {
            return false;
        }
        ...
        return true;
    }
    
    function password_is_valid(passwords) {
        for (var i = 0; i < password_validators.length; i++) {
            var validator = password_validators[i];
            if (!validator.fails(passwords)) {
                alert(validator.message);
                return false;
            }
        } 
        return true;
    }
    
    var password_validators = [
        {
            fails: function(passwords) {
                return passwords.new_ === '' && passwords.retyped === '';
            },
            message: 'No password provided'
        },
        {
            fails: function(passwords) {
                return passwords.new_ !== .passwordsretyped;
            },
            message: 'Passwords do not match'
        },
        ...
    ];
    
    $('change#u password_form')。关于('submit',函数(e){
    var data=收集_数据();
    如果(!data_是有效的(data)){
    e、 预防默认值();
    }否则{
    //提交。
    }
    });
    函数collect_data(){
    返回{
    密码{
    新密码:$('#新密码').val(),
    重新键入:$(“#重新键入密码”).val()
    },
    ...
    };
    }
    函数数据\u有效(数据){
    如果(!password_有效(data.passwords)){
    返回false;
    }
    ...
    返回true;
    }
    功能密码\u有效(密码){
    对于(var i=0;i
    诀窍是在变量中存储二进制错误标志,您只需对每个字段执行非嵌套的if/else计算。对于每次评估,将错误标志更新为
    true
    ,然后将错误的性质推送到数组中。在所有if/else语句之后,只需检查错误标志是否仍然为true或false。如果为false,则获取错误数组中的第一个元素。