【发布时间】:2012-02-21 03:04:18
【问题描述】:
我的视图模型中有 2 个文本字段,text1 和 text2。我需要验证是否输入了 text1,然后必须输入 text2,反之亦然。在视图模型的自定义验证中如何实现这一点?
谢谢。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 validation
我的视图模型中有 2 个文本字段,text1 和 text2。我需要验证是否输入了 text1,然后必须输入 text2,反之亦然。在视图模型的自定义验证中如何实现这一点?
谢谢。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 validation
您可以使用实现 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,则模型有效,否则无效。
【讨论】:
查看 mvc 万无一失的验证,它会进行条件验证。在 nuget 或 http://foolproof.codeplex.com
上找到它编辑 以上真的很老了
我建议任何现代的东西都使用 MVC Fluent Validation https://docs.fluentvalidation.net/en/latest/aspnet.html
【讨论】:
你可以使用 JQuery,像这样:
$("input[x2]").hide();
$("input[x1]").keypress(function() {
var textValue = ("input[x1]").val();
if(textValue)
$("input[x2]").show();
})
【讨论】:
如果你想在你的模型上使用数据注释验证器和验证属性,你应该看看这个: "attribute dependent on another field"
【讨论】: