4

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.