Validation In ASP.NET MVC

ammar atef
3 min readJun 23, 2021

In this example we are going to write a DateGreaterThan Validator to check the Date of one property is greater than the value of another property.

First of all, we need to create a class DateGreaterThanAttribute

then we Add Namespaces

After that we make our Class inherits from ValidationAttribute, IClientValidatable in the Constructor we receive the name of the other property that we would like to compare our value to it, then we can implement IsValid method.

we have two parameters :

  1. value is an object it contains the value for our Field, we cast it to DateTime to can use it for comparison.
  2. validationContext,we can get the value of the second property that we use for our comparison.

Then we compare the two Dates if firstValue greater than secondValue then we return ValidationResult.Success if it’s not we return new Object from

ValidationResult with FormatErrorMessage.

we Implement GetClientValidationRules method that you need to implement has one simple function. Using the metadata parameter, you are required to construct one or more ModelClientValidationRules which are returned from the method and used by the framework to output the client-side HTML5 data-* attributes that are necessary for client-side validation.

→ ValidationType should be unique.

ValidationParameters: it will contain the name(Id in frontEnd of the Element)of Another property that I would compare our value to it.

The Second Part we Create a method in frontEnd to use it.

in the first part we have the firstValue and the OtherProperty name that we have from the backend with Key datetocomparefieldname, params will hold the value that can get it using the key datetocomparefieldname,

we have the value for the first Field and the Id for the second Field

using it we can get the value and compare if the first value is greater than the second then we return True if not we return false when we return false it fires the html attributes and show the Error Message.

You can see the data -* attributes there

<input class=”form-control input — datepicker4" data-val=”true” data-val-date=”The field Contract Start Date must be a date.” data-val-dategreaterthan=”Contract Start Date should be greater than Opening Offers Date.” data-val-dategreaterthan-datetocomparefieldname=”OpeningOffersDate” id=”ContractStartDate” name=”ContractStartDate” type=”text” value=”2021–06–27">

--

--

ammar atef

Senior .Net & SharePoint Developer | Data Scientist