Javascript验证-组验证-如果输入了一个,则所有都是必需的

Javascript验证-组验证-如果输入了一个,则所有都是必需的,javascript,jquery,validation,Javascript,Jquery,Validation,仅使用jQuery(不是验证插件)我就设计了一种实现“如果一个,那么所有”需求的方法,但它一点也不优雅 我想知道是否有人能想出一个更优雅的解决方案?这一个使用了一些循环嵌套,我真的不满意它 if ($("[data-group]")) { //Store a simple array of objects, each representing one group. var groups = []; $("[data-group]").each(function () {

仅使用jQuery(不是验证插件)我就设计了一种实现“如果一个,那么所有”需求的方法,但它一点也不优雅

我想知道是否有人能想出一个更优雅的解决方案?这一个使用了一些循环嵌套,我真的不满意它

if ($("[data-group]")) {
    //Store a simple array of objects, each representing one group.
    var groups = [];
    $("[data-group]").each(function () {
        //This function removes an '*' that is placed before the field to validate
        removeCurError($(this));
        var groupName = $(this).attr('data-group');
        //If this group is already in the array, don't add it again
        var exists = false;
        groups.forEach(function (group) {
            if (group.name === groupName)
                exists = true;
        });
        if (!exists) {
            var groupElements = $("[data-group='" + groupName + "']");
            var group = {
                name: groupName,
                elements: groupElements,
                trigger: false
            }
            group.elements.each(function () {
                if (!group.trigger) {
                    group.trigger = $(this).val().length !== 0;
                }
            });
            groups.push(group);
        }
    });
    //Now apply the validation and alert the user
    groups.forEach(function (group) {
        if (group.trigger) {
            group.elements.each(function () {
                //Make sure it's not the one that's already been filled out
                if ($(this).val().length === 0)
                    // This function adds an '*' to field and puts it into a
                    // a sting that can be alerted
                    appendError($(this));
            });
        }
    });

您不必将组存储在数组中,只要在需要验证$elements时调用validateGroups函数即可。下面是一个工作示例

HTML

1组
第2组
验证
Javascript

function validateGroups($elements) {
    $elements.removeClass('validated');
    $elements.each(function() {

        // Return if the current element has already been validated.
        var $element = $(this);
        if ($element.hasClass('validated')) {
            return;
        }

        // Get all elements in the same group.
        var groupName = $element.attr('data-group');
        var $groupElements = $('[data-group=' + groupName + ']');
        var hasOne = false;

        // Check to see if any of the elements in the group is not empty.
        $groupElements.each(function() {
            if ($(this).val().length > 0) {
                hasOne = true;
                return false;
            }
        });

        // Add an error to each empty element if the group
        // has a non-empty element, otherwise remove the error.
        $groupElements.each(function() {
            var $groupElement = $(this);
            if (hasOne && $groupElement.val().length < 1) {
                appendError($groupElement);
            } else {
                removeCurError($groupElement);
            }
            $groupElement.addClass('validated');
        });
    });
}

function appendError($element) {
    if ($element.next('span.error').length > 0) {
        return;
    }
    $element.after('<span class="error">*</span>');
}

function removeCurError($element) {
    $element.next().remove();
}

$(document).ready(function() {

    $('button').on('click', function() {
        validateGroups($("[data-group]"));
    });

});
函数验证组($elements){
$elements.removeClass('validated');
$elements.each(函数(){
//如果当前元素已被验证,则返回。
var$element=$(此);
if($element.hasClass('validated')){
返回;
}
//获取同一组中的所有元素。
var groupName=$element.attr('data-group');
var$groupElements=$('[data group='+groupName+']);
var hasOne=假;
//检查组中是否有任何元素不是空的。
$groupElements.each(函数(){
如果($(this.val().length>0){
hasOne=正确;
返回false;
}
});
//如果组
//具有非空元素,否则删除错误。
$groupElements.each(函数(){
var$groupElement=$(此值);
if(hasOne&&$groupElement.val().length<1){
appendError($groupElement);
}否则{
删除错误($groupElement);
}
$groupElement.addClass('validated');
});
});
}
函数错误($element){
if($element.next('span.error')。长度>0){
返回;
}
$element.after('*');
}
函数removeCurError($element){
$element.next().remove();
}
$(文档).ready(函数(){
$('button')。在('click',function()上{
验证组($(“[数据组]”));
});
});

您可能会从这个解决方案中得到一些启发。基本上,在发送表单之前,在“提交”按钮上简化并测试您的解决方案(这不起作用)。在本例中,我只需测试第一个复选框的值是否为真,然后警告或选中所需的复选框。这些可以是你喜欢的任何东西。祝你好运


对于jquery:

checkTest = function(){

    var isChecked = $('input')[0].checked;

    if(isChecked){
        alert('form is ready: input 0 is: '+isChecked);
    }else{
        $('input')[1].checked = true;
        $('input')[2].checked = true;
    }    
};

//create a bunch of checkboxes
$('<input/>', {
    type: 'checkbox',
    html: 'tick'
}).prependTo('form');

$('<input/>', {
    type: 'checkbox',
    html: 'tick'
}).prependTo('form');

$('<input/>', {
    type: 'checkbox',
    html: 'tick'
}).prependTo('form');
checkTest=函数(){
var isChecked=$('input')[0]。已选中;
如果(已检查){
警报('表单已准备就绪:输入0为:'+isChecked);
}否则{
$('input')[1]。选中=true;
$('input')[2]。选中=true;
}    
};
//创建一组复选框
$('', {
键入:“复选框”,
html:“勾选”
}).prependTo(“表格”);
$('', {
键入:“复选框”,
html:“勾选”
}).prependTo(“表格”);
$('', {
键入:“复选框”,
html:“勾选”
}).prependTo(“表格”);

我不确定这与我的问题有什么关系。啊,这是一件令人愉快的事情。我不得不做一些调整以匹配我的应用程序,但这比我使用的要好得多。非常感谢你,大卫!这对我来说非常好,但我有一个问题。如果所有内容都经过验证和填写,那么在代码中哪里可以返回真值?如果validateGroups()返回缺少的字段,我想阻止表单提交。
<form>    
    <input type="button" onclick="return checkTest()" value="test"/>
</form>
checkTest = function(){

    var isChecked = $('input')[0].checked;

    if(isChecked){
        alert('form is ready: input 0 is: '+isChecked);
    }else{
        $('input')[1].checked = true;
        $('input')[2].checked = true;
    }    
};

//create a bunch of checkboxes
$('<input/>', {
    type: 'checkbox',
    html: 'tick'
}).prependTo('form');

$('<input/>', {
    type: 'checkbox',
    html: 'tick'
}).prependTo('form');

$('<input/>', {
    type: 'checkbox',
    html: 'tick'
}).prependTo('form');