Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range annotation between nothing and 100?

I have a [Range] annotation that looks like this:

[Range(0, 100)]
public int AvailabilityGoal { get; set; }

My webpage looks like this:

<%=Html.TextBoxFor(u => u.Group.AvailabilityGoal)%>

It works as it should, I can only enter values between 0 and 100 but I also want the input box to be optional, the user shouldn't get an validation error if the input box is empty. This has nothing to do with the range but because the type is an integer. If the user leaves it empty it should make AvailabilityGoal = 0 but I don't want to force the user to enter a zero.

I tried this but it (obviously) didn't work:

[Range(typeof(int?), null, "100")]

Is it possible to solve this with Data Annotations or in some other way?

Thanks in advance.

Bobby

like image 454
Bobby Avatar asked May 26 '10 13:05

Bobby


People also ask

What is System ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

What is range attribute?

The range attribute allows a numeric range to be specified for a slot when a numeric value is used in that slot. If a numeric value is not used in that slot, then no checking is performed.

What is an attribute in data annotation?

We'll use the following Data Annotation attributes: Required – Indicates that the property is a required field. DisplayName – Defines the text to use on form fields and validation messages. StringLength – Defines a maximum length for a string field. Range – Gives a maximum and minimum value for a numeric field.


2 Answers

You shouldn't have to change the [Range] attribute, as [Range] and other built-in DataAnnotations validators no-op when given an empty value. Just make the property itself of type int? rather than int. Non-nullable ValueType properties (like int) are always automatically required.

like image 106
Levi Avatar answered Sep 23 '22 13:09

Levi


I guess you could override the Range object and add this behaviour.

public class OptionalRange : RangeAttribute {
    public override bool IsValid(object value) {
        if (value == null || (int)value == 0) return true;
        return base.IsValid(value);
    }
}
like image 38
Robert Massa Avatar answered Sep 21 '22 13:09

Robert Massa