What is the MVC verification system

I rated xVal as a framework for checking objects in the ASP.Net MVC Framework. I recently discovered that every time a validation rule is violated, xVal triggers an excpetion throw. It seems wrong to me. For example, when a user fills out a form and forgets to fill in three required fields, three exceptions will be thrown. Is this a good practice? (Edit: I also read this, so I think this is not a good practice)

What is your experience using xVal? Is there a good alternative check system that does not throw exceptions?

thanks

(PS: I notice that many are reading this, just to let you know. Now I'm using Fluent Validation )

+3
source share
3 answers

No, it is not a good practice to show exceptions instead of some simple messages, because nothing is seriously wrong ... Instead, you should fill in ModelStatethese errors and display them on the form with

Html.ValidationMessage("EntityPropertyName");

xVal supports all of this. Like client-side validation before the form is submitted back.

Some code

DataAnnotations ( ), , , Validate(). T4, , ...

public IEnumerable<ErrorInfo> Validate()
{
    IList<ErrorInfo> errors = DataAnnotationsValidationRunner.GetErrors(this).ToList<ErrorInfo>();
    return errors.AsEnumerable();
}

, , :

IEnumerable<ErrorInfo> errors = entityObjectInstance.Validate();
if (errors.Any())
{
    new RulesException(errors).AddModelStateErrors(filterContext.Controller.ViewData.ModelState, entityPropertyName);
}

, , , . ModelState.IsValid().

, ( -):

public static class DataAnnotationsValidationRunner
{
    public static IEnumerable<ErrorInfo> GetErrors(object instance)
    {
        var metadataAttribute = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
        var metaClass = metadataAttribute != null ? metadataAttribute.MetadataClassType : instance.GetType();
        var metaClassProperties = TypeDescriptor.GetProperties(metaClass).Cast<PropertyDescriptor>();
        var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();

        return from metaProp in metaClassProperties
               join modelProp in modelClassProperties on metaProp.Name equals modelProp.Name
               from attribute in metaProp.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(modelProp.GetValue(instance))
               select new ErrorInfo(metaProp.Name, attribute.FormatErrorMessage(string.Empty), instance);
    }
}

MVC 2

Asp.net MVC 2 Beta 2 , xVal. , , , , .

+3

, xVal , Castle Validators, . Exception , ModelState, .

try
{
  // execute validation runner
}
catch (RulesException ex)
{
   ex.AddModelStateErrors(ModelState, "prefix");
}

ASP.NET MVC v2 .

+2

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


All Articles