Reputation: 1960
In my project I have a few instances where the user needs to supply an amount (in pounds and pence) as a decimal and it has to be within the Int32 range so it can be converted for the database. I assumed it would be possible to do this:
/// <summary>
/// Range attribute to ensure that entered value can be converted to an int32
/// </summary>
public class PoundsAndPenceAttribute : RangeAttribute
{
public PoundsAndPenceAttribute(double minimum = (double)int.MinValue / 100, double maximum = (double)int.MaxValue / 100)
: base(minimum, maximum)
{
}
}
Unfortunately it doesn't produce the client-side JavaScript data-val range attribute, although it does validate it server-side. Is there a better way of doing this or do I have to write a custom validator?
Upvotes: 4
Views: 1769
Reputation: 201
try to implement IClientValidatable interface :
public class PoundsAndPenceeAttribute : RangeAttribute, IClientValidatable
{
public LocalizeRange(double minimum = (double)int.MinValue / 100, double maximum = (double)int.MaxValue / 100)
: base(minimum, maximum)
{
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "range"
};
rule.ValidationParameters.Add("min", Minimum);
rule.ValidationParameters.Add("max", Maximum);
yield return rule;
}
}
It should do the job.
Upvotes: 5