【问题标题】:Data Validations in ASP.net MVC applicationASP.net MVC 应用程序中的数据验证
【发布时间】:2017-07-09 12:12:00
【问题描述】:

我正在使用 MVC 中的 asp.net 开发一个应用程序。现在我必须为每个输入提供验证。因为我是 MVC 的新手,并且对如何提供验证不太了解。谁能帮我搞定这个。

上传

在上面的代码中接受最大日期值和最小数据值。 它应该首先接受最小日期(发布日期)值和第二个最大日期(到期日期)。但现在它的工作相反。 谁能帮我提供验证。

【问题讨论】:

    标签: asp.net-mvc validation asp.net-mvc-4


    【解决方案1】:

    这里可以设置两种方式Validation 一个是客户端,另一个是服务器端

    下面给出的服务器端验证

    您可以将签发日期与当前日期/时间进行比较,也可以将到期日期与签发日期进行比较

    public class MyClass : IValidatableObject
    {               
        [Required(ErrorMessage="issued date and time cannot be empty")]
        //validate:Must be greater than current date
        [DataType(DataType.DateTime)]
        public DateTime issuedDateTime { get; set; }
    
        [Required(ErrorMessage="expiry date and time cannot be empty")]
        //validate:must be greater than issuedDate
        [DataType(DataType.DateTime)]
        public DateTime expiryDateTime { get; set; }       
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> results = new List<ValidationResult>();
    
            if (issuedDateTime < DateTime.Now)
            {
                results.Add(new ValidationResult("issued date and time must be greater than current time", new []{"issuedDateTime"}));
            }
    
            if (expiryDateTime <= issuedDateTime)
            {
                results.Add(new ValidationResult("expiryDateTime must be greater that issuedDateTime", new [] {"expiryDateTime"}));
            }
    
            return results;
        }     
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 2014-06-19
      • 1970-01-01
      相关资源
      最近更新 更多