我正在开发一个使用jquery-form-validator-rails gem进行表单字段验证的group rails app。我可以使用字段上的数据对象执行简单验证,如下所示:
<%= f.text_field(:name , class: "form-control", data: { :validation => "required validate_max_length length255", "validation-error-msg" => "Required Field, 255 characters max"}) %>
但是,我无法弄清楚如何添加条件验证规则。我需要仅在另一个字段包含特定值时才需要特定字段(例如:仅当选择字段#component_id包含'other'作为值时才需要#other_component_id。)
我尝试在$ .validate()调用中添加规则,但它们似乎不适用。
$().validate({
rules: {
other_component_id: {
required: function(element) {
return $('#component_id').val().includes('other');
}
}
}
});
将validate()方法应用于特定表单也不起作用。
因为这个应用程序是共享的,所以我必须使用jquery-form-validator-rails gem进行表单验证。
答案 0 :(得分:0)
没关系。事实证明我使用了不正确的格式来应用验证(尽管'required'验证工作正常,但最大长度不是)。我改为使用这种格式:
<%= f.text_field(:name , class: "form-control", data: { :validation => 'length', 'validation-length' => '1-255',
'validation-error-msg' => 'Required Field, 255 characters max'}) %>
然后我可以添加自定义验证器并将其应用到我的字段中。
JS:
$.formUtils.addValidator({
name : 'comp_required',
validatorFunction : function(value, $el, config, language, $form) {
if ($('#component_id').val().includes('other')) {
if (value.length > 0 && value.length <= 32) {
return true;
}
} else {
return true;
}
},
errorMessage : 'You must enter a new component name. Max length = 32',
errorMessageKey: 'badComponentName'
});
如果有人建议采用更有效的条件验证方法,我很想听听它们。