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)
>
To create a custom validation attribute in .Net Core
, you need to inherit from IModelValidator
and implement Validate
method.
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)
};
}
}
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 validatedcontext.Container
: returns the object that contains the propertycontext.ActionContext
: provides context data and describes the action method that processes the requestcontext.ModelMetadata
: describes the model class that is being validated in detailThis validation attribute doesn't work with Client Validation, as requested in OP.