Validation of dates in the Asp Net Core model?

2

I have a template and wanted to validate the end date (which should be equal to or greater than the start date)

public class MyModel
{
    [Key]
    public int ModelId { get; set; }

    [Display(Name = "Início")]
    [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
    public DateTime? StartDate { get; set; }

    [Display(Name = "Fim")]
    [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
    public DateTime? FinishDate { get; set; }

}

Any idea how to validate one field based on another in a template?

    
asked by anonymous 15.08.2017 / 17:23

1 answer

2

Previous version of ASPNET CORE

A custom class must be created that inherits from the abstract class ValidationAttribute for server validation and the IClientValidatable interface for client validations, the basic example to validate if one date is greater than or equal to another is:

Create a class and inherit and implement respectively ValidationAttribute and IClientValidatable :

public class DateTimeCompareAttribute : 
        ValidationAttribute, IClientValidatable

{
    public string NameCompare { get; set; }
    public DateTimeCompareAttribute(string nameCompare)
    {
        NameCompare = nameCompare;
    }
    protected override ValidationResult IsValid(object value, 
                                                ValidationContext validationContext)
    {            
        if (validationContext.ObjectInstance != null)
        {
            Type _t = validationContext.ObjectInstance.GetType();
            PropertyInfo _d = _t.GetProperty(NameCompare);
            if (_d != null)
            {
                DateTime _dt1 = (DateTime)value;
                DateTime _dt0 = (DateTime)_d
                     .GetValue(validationContext.ObjectInstance, null);
                if (_dt1 != null &&
                    _dt0 != null &&
                    _dt0 <= _dt1)
                {
                    return ValidationResult.Success;
                }
            }
        }
        return new ValidationResult("Final Date is less than Initial Data");
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
                                                  ModelMetadata metadata, 
                                                  ControllerContext context)
    {
        ModelClientValidationRule rules = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "datetimecompare"
        };

        rules.ValidationParameters.Add("param", NameCompare);            
        yield return rules;
    }
}

After creating this class you have to configure in the class that will be validated by this attribute as follows:

public class MyModel
{
    [Key]
    public int ModelId { get; set; }

    [Display(Name = "Início")]
    [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
    public DateTime? StartDate { get; set; }

    [Display(Name = "Fim")]
    [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
    //configuração para verificar se a data é maior ou igual a que foi dita no parâmetro
    [DateTimeCompare("StartDate")] 
    public DateTime? FinishDate { get; set; }

}

This configuration already validates the data on the server, but to get a complete validation it is legal to add a% excerpt%

15.08.2017 / 18:27