如何在客户端验证中避免冗余条件?

时间:2013-10-10 19:25:21

标签: javascript json

我有使用许多条件语句的代码,并且变得复杂。我正在寻找一种更有效的方法来验证输入。

我的代码收到服务器端验证的结果为JSON。对于许多输入中的每一个,如果输入的值无效,则服务器返回相应的false。条件语句适当地修改UI。这是一个示例:

else if((data.address===false)&&(data.city===false)&&(data.municipality===false))
{
    $('#adrserror').html('You have to put an address, city and municiplaity.'); 
    $('label.error').hide();
    $('.openpaddress').find('input').prop('readonly', false);
}
else if((data.address===false)&&(data.city===false))
{
    $('#adrserror').html('You have to fill the address and the city fields.'); 
    $('label.error').hide();  
    $('.openpaddress').find('#municipality').prop('readonly', true).css('border', '0px');   
}
else if((data.city===false)&&(data.municipality===false))
    ...

HTML只包含三个带有附带标签的输入元素(用于地址,城市和自治市)。

1 个答案:

答案 0 :(得分:2)

这样的事情:

var missing = [];
var fields = ['address', 'city', 'municipality'];
for (var i = 0; i < fields.length; i++) {
    var f = fields[i];
    if (data[f] === false) {
        missing.push(f);
    }
}
if (missing.length > 0) {
    $('#adrserror').text('Please fill in fields: ' + missing.join(', '));
}
相关问题