Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my int? value being validated as if it was required?

I have an int? view model property that is validated at client-side as if it was required. That is, if I leave the field blank, it will not submit. The same does not happen for string properties.

The HTML rendered for my editor is:

<input type="text" value="" name="StatusIdSearch" id="StatusIdSearch" data-val-number="The field Status must be a number." data-val="true" class="text-box single-line">

I believe that data-val-number is causing an error because nothing is not a number, but I cannot determine why.

Any ideas?

Edit

The view-model:

public class CompromissoSearchModel
{
        // other properties removed for the sake of clarity

        [Display(Name = "Status")]
        [EnumDataType(typeof(StatusCompromisso))]
        public int? StatusIdSearch { get; set; }

       // other properties removed for the sake of clarity
}
like image 682
André Pena Avatar asked Jan 31 '12 18:01

André Pena


2 Answers

The message you are seeing it's not related to a required field validation. You're gettings this because ClientDataTypeModelValidatorProvider adds client numeric validation and it ignores if the type is nullable or nor not. You can check the code yourself:

private static IEnumerable<ModelValidator> GetValidatorsImpl(
    ModelMetadata metadata, 
    ControllerContext context) 
{
    Type type = metadata.RealModelType;
    if (IsNumericType(type)) {
        yield return new NumericModelValidator(metadata, context);
    }
}

And the IsNumericType implementation:

private static bool IsNumericType(Type type) 
{
    // strip off the Nullable<>
    Type underlyingType = Nullable.GetUnderlyingType(type); 
    return _numericTypes.Contains(underlyingType ?? type);
}

Since the nullable is not considered you always get that validation. In terms of solution, you need to remove ClientDataTypeModelValidatorProvider from the used providers or maybe replace it with a custom one that does not ignore nullable.

like image 123
João Angelo Avatar answered Nov 07 '22 11:11

João Angelo


You should be able to add the following code to your Application_Start method in Global.asax file to fix this issue:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

like image 39
Scott Smith Avatar answered Nov 07 '22 09:11

Scott Smith