在2个字段上进行asp.net mvc验证-如果输入其他字段,则必须存在一个 [英] asp.net mvc validation on 2 fields - one must exist if other entered

查看:91
本文介绍了在2个字段上进行asp.net mvc验证-如果输入其他字段,则必须存在一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型中有2个文本字段,text1和text2.我需要验证是否输入了text1,然后必须输入text2,反之亦然.如何在视图模型的自定义验证中实现这一点?

I have 2 text fields, text1 and text2, in my view model. I need to validate if text1 is entered then text2 must be entered and vice versa. How can this be achieved in the custom validation in the view model?

谢谢.

推荐答案

您可以将实现IValidatableObject(来自System.ComponentModel.DataAnnotations命名空间)用于视图模型上的服务器端验证:

You can use implement IValidatableObject (from System.ComponentModel.DataAnnotations namespace) for the server side validation on your View Model:

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,则模型有效,否则,则无效.

Now it make sure if both Name and SecondName are set, or null, then model is valid, otherwise, it's not.

这篇关于在2个字段上进行asp.net mvc验证-如果输入其他字段,则必须存在一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆