Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrequired property keeps getting data-val-required attribute

I found the answer. Just add this to Application_Start:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Make the view-model value-types nullable. Then they won't be Required by default.

Note also if you put the attribute 'required="false"' in html 5 (if you set html 5 in your doctype meta data), it will see "required" and make it required. You can use dojo-data-props="required:false".


frennky's solution only removed data-val-required but in my case I still had data-val-number and data-val

I had to add the two lines below to Application_Start to get rid of everything.

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new DataAnnotationsModelValidatorProvider());

The problem is that the value of the hidden field is empty. This shouldn't happen if you use integer type. I suppose that the TagId property is defined as a nullable type in the Tag class. So either assign it a value before rendering the view or use an integer type:

[MetadataType(typeof(TagValidation))]
public partial class Tag
{
    public int TagId { get; set; }
    public string Name { get; set; }
}

so that the generated hidden field looks like this:

<input 
    data-val="true" 
    data-val-number="The field TagId must be a number." 
    data-val-required="The TagId field is required." 
    id="TagId" 
    name="TagId" 
    type="hidden" 
    value="0" 
/>

Also normally client side validation shouldn't be triggered for this hidden field.


jquery validate target cheking "disabled" html attribute.

$(function () { 
  $("#TagId").attr("disabled", "disabled") 
});

or use Nullable.

hope this code!


With MVC4 you can also use this:

@{ Html.EnableClientValidation(false); }
@Html.EditorForModel()
@{ Html.EnableClientValidation(true); }