我的视图模型中有2个文本字段text1和text2。我需要验证是否输入了text1,然后输入text2,反之亦然。在视图模型中的自定义验证中如何实现这一点?在2个字段上的asp.net mvc验证 - 其他输入时必须存在
谢谢。
我的视图模型中有2个文本字段text1和text2。我需要验证是否输入了text1,然后输入text2,反之亦然。在视图模型中的自定义验证中如何实现这一点?在2个字段上的asp.net mvc验证 - 其他输入时必须存在
谢谢。
可以使用实现对服务器端验证IValidatableObject
(从System.ComponentModel.DataAnnotations
命名空间)您的视图模型:
public class AClass : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public string SecondName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if((!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName)))
yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"});
}
}
现在,它使当然,如果Name和SecondName都设置了,或者null,那么model是有效的,否则它不是。
您可以使用jQuery,像这样:
$("input[x2]").hide();
$("input[x1]").keypress(function() {
var textValue = ("input[x1]").val();
if(textValue)
$("input[x2]").show();
})
如果你想使用数据注释验证和模型验证属性,你应该看看这个: “attribute dependent on another field”
看MVC万无一失验证它确实有条件的验证。在nuget上查找它或者http://foolproof.codeplex.com
仅供参考,我建议在使用验证摘要时不要返回验证结果中的字段。如果您返回验证结果中的两个字段,则验证摘要将包含两条消息,而不是预期的单条消息。 – 2015-03-31 17:22:05
你可以包含一些代码来说明如何使用它来注释类属性吗? – niico 2017-02-24 17:35:03