我正在使用 jQuery 进行一些表单验证,验证每个字段的 onblur。一切都工作得很好,除了当我对(依赖)字段进行分组时。我正在寻找的是一种只有在所有字段都被模糊后才验证这些字段的方法。它们可以分组为 jQuery 对象的集合,也可以分组为包含元素的子元素。
一个示例是由三个 < select > 元素组成的生日输入:
<fieldset>
<label for="bday_month">Birthday:</label>
<select name="userBirthday[month]" id="bday_month">
<option value="0">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
...
</select>
<select name="userBirthday[day]" id="bday_day">
<option value="0">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
...
</select>
<select name="userBirthday[year]" id="bday_year">
<option value="0">Year</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option value="1989">1989</option>
...
</select>
</fieldset>
就目前而言,验证函数与每个字段的blur() 事件相关联。分组字段将找到其依赖项并正确验证,但在字段之间切换时,会显示错误消息,因为用户尚未完成输入。
我尝试将blur() 事件添加到字段集并绑定(bind)自定义事件,但都不太成功。
作为引用,以下是我目前的blur() 函数:
fieldBlur = function(e){
// Array of objects w/specific validation functions, arguments, etc.
validators = $(this).data('validators');
// Process each validator separately
for(key in validators){
validator = validators[key];
$field = validator.$field;
// Extracts the value from grouped fields as an array
val = valHelper($field);
// Call one of the pre-defined validation functions
functionResponse = eval(validator.options.functionName + "(val, validator.options.functionArgs);");
if(!functionResponse){
validator.$error.find('.text').text(validator.options.errorMsg);
validator.$info.hide();
validator.$error.show();
e.preventDefault();
break; // Only display the first error
} else {
validator.$error.hide();
}
}
return true;
};
提前致谢,如果更多代码/解释会有帮助,请告诉我。
最佳答案
终于有东西可以工作了。我会尽力在这里概述它。
blur()
事件附加到每个字段blur()
调用的函数setTimeout(function(){ fieldBlurHelper(e); }, 100);
在
fieldBlurHelper()
中,我检查当前是否有任何分组字段通过应用于每个具有焦点的元素的类获得焦点:$field.filter('.hasFocus');
如果没有任何字段具有焦点,我将运行验证器
完整(简化)fieldBlur 函数:
fieldBlur = function(e){
fieldBlurHelper = function(e){
// Array of validation data (function name, args, etc.)
validators = $(e.target).data('validators');
for(key in validators){
validator = validators[key];
// $field contains all the dependent fields (determined on ready())
$field = validator.$field;
// If any of the dependent fields have focus, don't bother with validation
if($field.filter('.hasFocus').length > 0){ break; }
// Extracts value as an array for all the dependent fields (.val() only returns the first)
val = valHelper($field);
functionResponse = eval(validDater.options.functionName + "(val, validDater.options.functionArgs);");
if(!functionResponse){
console.log('error!');
break; // we only want to show the user one error at a time
} else {
console.log('valid!');
}
}
};
// running the function after the timeout allows the fields to lose focus
setTimeout(function(){ fieldBlurHelper(e); }, 100);
};
关于javascript - jQuery - 多场模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1323813/