I've got custom validation that checks another field, and then determines if the field in question is within a certain number range. It works fine whenever the user enters a number. However, if the user passes in a non-number, this non-number (the value
parameter) doesn't get passed to the validation. Instead, null
is passed to the validation. I'd rather have the number with the commas be passed in. Instead, the user is presented with a cryptic "The value XXX is not valid for XXX
which isn't helpful. I've also got [Required]
and [Numeric]
data annotations on this field. These usually catch any issues. However, if the user enters a valid number with a comma, the value won't get passed to my custom validation. I'm not sure where the issue is happening. Any thoughts? I've tried stripping out the commas via javascript, but the value being passed to my custom validation is still null. Here's my custom validation that is being called:
public sealed class RequiresRangeAmount : ValidationAttribute
{
public RequiresRangeAmount(string property)
{
Property = property;
}
public string Property { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(Property);
if (property != null)
{
var loanSubType = (int)property.GetValue(validationContext.ObjectInstance, null);
if (loanSubType == LoanSubTypeConstants.Visa|| loanSubType == LoanSubTypeConstants.Visa2)
{
var valueConverted = Convert.ToDecimal(value);
if (valueConverted < 5000 || valueConverted > 75000)
{
return new ValidationResult(ErrorMessage);
}
}
}
return null;
}
}
Here is is being used:
[Required]
[Numeric]
[RequiresRangeAmount("LoanSubType", ErrorMessage = "A VISA must be in XXX range.")]
[DisplayName("Requested Loan Amount")]
public decimal? RequestedAmount { get; set; }
Front-end to strip the commas out doesn't help:
$("#mainForm").submit(function() {
var strippedCommasAmount = $("#RequestedAmount").val().replace(/,/g, '');
$("#RequestedAmount").val(strippedCommasAmount);
});