The built-in validations exposed in the framework may be solving most of our technical validation problems, but there may be some business needs/requirements that require additional provision on top of built-in validations.
The custom validation can be performed at two levels:
- Field level
- Class level
The field-level custom validator can be created using the following:
- Inherit the custom validation class from the
ValidationAttribute
base type - Override the
IsValid
method and handle your business validation - The
IsValid
method accepts two parameters—value
andvalidationContext
- The
value
field is the actual field value against which the attribute is configured - The
validationContext
field would haveObjectInstance
of the model that contains the configured field
In our blogging system, we can provide a business validation to the publication date; it needs a validation that prohibits the user from publishing the post in a past date. Let's call the custom validation attribute FutureOnly
and...