Hi friends,
I had a requirement, where I need to check one value is always greater than other.
I have created a custom data annotation as follows:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace AmericanExpress.GFES.INXSOnlineAdmin.WP.CustomValidation
{
public class GreaterThanAttribute : ValidationAttribute, IClientValidatable
{
public string PropertyNameToCompare { get; set; }
public string ErrorMessage { get; set; }
public GreaterThanAttribute(string propertyNameToCompare, string errorMessage)
{
PropertyNameToCompare = propertyNameToCompare;
ErrorMessage = errorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyToCompare = validationContext.ObjectType.GetProperty(PropertyNameToCompare);
if (propertyToCompare == null)
{
return new ValidationResult(
string.Format("Invalid property name '{0}'", PropertyNameToCompare));
}
var valueToCompare = propertyToCompare.GetValue(validationContext.ObjectInstance, null);
bool valid;
if (value is decimal && valueToCompare is decimal)
{
valid = ((decimal)value) > ((decimal)valueToCompare);
}
else
{
return new ValidationResult("Compared properties should be numeric and of the same type.");
}
if (valid)
{
return ValidationResult.Success;
}
return new ValidationResult(
string.Format("{0} must be greater than {1}",
validationContext.DisplayName, PropertyNameToCompare));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = ErrorMessage;
rule.ValidationParameters.Add("other", PropertyNameToCompare);
rule.ValidationType = "greaterthan";
yield return rule;
}
}
}
In Model:
[Required(ErrorMessage = "Please enter minimum range")]
public decimal RangeMin { get; set; }
[Required(ErrorMessage = "Please enter maximum range")]
[GreaterThan("RangeMin","Max range must be greater than Min")]
public decimal RangeMax { get; set; }
In Partial View:
<script>
$(document).ready(function () {
$.validator.unobtrusive.parse("#frmSavePromotion");
$.validator.addMethod('greaterthan', function (value, element) {
return $(element).is(":checked");
});
$.validator.unobtrusive.adapters.add('greaterthan', [], function (options) {
options.messages['greaterthan'] = options.message;
options.rules['greaterthan'] = options.params;
});
});
</script>
I have tried above, but it is working for me.
Can anyone tell me where I'm going wrong?
Thanks in advance