收集的不显眼的审定 [英] Unobtrusive validation of collection
本文介绍了收集的不显眼的审定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模型包含集合:
public ICollection<int> ChildAges { get; set; }
这是可以添加到年龄的动态列表,这是通过JQuery的所有控制。
This is a dynamic list of ages that can be added to, this is all controlled via JQuery.
给我
<select name="ChildAges">...</select>
<select name="ChildAges">...</select>
<select name="ChildAges">...</select>
etc...
如果我添加标准要求
属性,如果集合中的任何一个值设置验证返回true。
If I add the standard Required
attribute the validation returns true if any one value in the collection is set.
我如何可以验证所有的 ChildAges
的形式设置?
How can I validate that all ChildAges
in the form are set?
推荐答案
我创建了一个新的自定义 IClientValidatable
属性:
I created a new custom IClientValidatable
attribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MultipleRequiredValuesAttribute : RequiredAttribute, IClientValidatable
{
#region IClientValidatable Members
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = base.ErrorMessage,
ValidationType = "multiplerequiredvalues"
};
return new[] { clientValidationRule };
}
#endregion
}
和应用这对我的模型:
[DisplayName("Ages(s)")]
[MultipleRequiredValues(ErrorMessage = "You must provide ages for all children in all rooms")]
public ICollection<int> ChildAges { get; set; }
我可以再添加JQuery的一面:
I can then add the JQuery side:
(function ($) {
$.validator.addMethod('multiplerequiredvalues', function (value, element) {
if ($(element).is(':visible')) {
var returnVal = true;
var name = $(element).attr('name');
var elements;
if ($(element).is('input')) {
elements= $('input[name='+name+']');
}
else
{
elements= $('select[name='+name+']');
}
elements.each(function() {
if ($(this).is(':visible'))
{
returnVal = $(this).val() != "" && $(this).val() != null;
}
});
return returnVal;
}
else {
return true;
}
});
$.validator.unobtrusive.adapters.addBool("multiplerequiredvalues");
} (jQuery));
注意如果该元素是不可见的,这也将返回true
Note this also returns true if the element isn't visible
这篇关于收集的不显眼的审定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文