How can I keep ViewModel validation in sync with model validation?

I use the Entity Framework Code First approach, which means that my model needs data annotation attributes to create the database. And I want the check to be on my model.

I have some opinions on my website that may post some information. But this information is not the whole model, and if I had to verify it, the verification failed.

For example, I could be a model with such necessary properties: Title, Text, X... But then I might have an idea that will only publish value Text. To do this, I create a ViewModel (which also has other elements that are not model bound). But how can I check Textin this case? I need to have the same validation as the model property Text.

Is there a way to have the same checks for Model and ViewModel without duplicating code?


This is an attempt that just won't work ...

I was thinking of creating a custom attribute that associates validations with a model:

/* This wouldn't work */
public class PropertyValidationAttribute : ValidationAttribute
{
    public Type Type { get; set; }

    public string PropertyName { get; set; }

    public PropertyValidationAttribute(Type type, string propertyName)
    {
        Type = type;
        PropertyName = propertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var attrs = Type.GetProperty(PropertyName).GetCustomAttributes(typeof(ValidationAttribute), true) as IEnumerable<ValidationAttribute>;

        if (attrs != null)
        {
            foreach (var attr in attrs)
            {
                return attr.GetValidationResult(value, validationContext);
            }
        }

        return base.IsValid(value, validationContext);
    }
}

, ValidationAttribute , , , . , , ...

+4
2

, , , , , , .

, . -, EF MVC. , EF MaxLength MinLength, MVC StringLength.

-, , ?

, , ... , . ... , . PLUS , ...

...

0

, - , . , , , .

0

Source: https://habr.com/ru/post/1546762/


All Articles