ASP.NET Core - Custom model validation

前端 未结 2 1691
滥情空心
滥情空心 2021-02-07 02:07

In MVC when we post a model to an action we do the following in order to validate the model against the data annotation of that model:

if (ModelState.IsValid)
         


        
2条回答
  •  你的背包
    2021-02-07 02:50

    To create a custom validation attribute in .Net Core, you need to inherit from IModelValidator and implement Validate method.

    Custom validator

    public class ValidUrlAttribute : Attribute, IModelValidator
    {
        public string ErrorMessage { get; set; }
    
        public IEnumerable Validate(ModelValidationContext context)
        {
            var url = context.Model as string;
            if (url != null && Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                return Enumerable.Empty();
            }
    
            return new List
            {
                new ModelValidationResult(context.ModelMetadata.PropertyName, ErrorMessage)
            };
        }
    }
    

    The model

    public class Product
    {
        public int ProductId { get; set; }
    
        [Required]
        public string ProductName { get; set; }
    
        [Required]
        [ValidUrl]
        public string ProductThumbnailUrl { get; set; }
    }
    

    Will this approach give opportunity to work with "ModelState.IsValid" property in controller action method?

    Yes! The ModelState object will correctly reflect the errors.

    Can this approach be applied to the model class? Or it can be used with model class properties only?

    I don't know if that could be applied onto class level. I know you can get the information about the class from ModelValidationContext though:

    • context.Model: returns the property value that is to be validated
    • context.Container: returns the object that contains the property
    • context.ActionContext: provides context data and describes the action method that processes the request
    • context.ModelMetadata: describes the model class that is being validated in detail

    Notes:

    This validation attribute doesn't work with Client Validation, as requested in OP.

提交回复
热议问题