views:

414

answers:

3

Im trying to create a custom version of the RequiredAttribute to replace the built in one and I've got it working for properties that have strings values, but with properties that are DateTime or integer for example, the default RequiredAttribute seems to be applied automatically (IF the property is not nullable!)

My problem is that i want to be able to specify a DateTime property as required using my custom required validator which gets the error message from a resources file (I don't want to have to tell the RequiredAttribute the type of the resource file and the key every time i apply it. That is why I'm making a custom one.)

How can i prevent the framework from applying the required attribute to properties of type DateTime and int etc without changing them to nullable.

Thanks

+8  A: 

Found it! I put this in the Global.asax.cs file

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

The DataAnnotationsModelValidatorProvider class has a static property called "AddImplicitRequiredAttributeForValueTypes" which by default must be true, and setting it to false fixed the problem.

(For anyone trying to do the same sort of things that finds this entry, I'm documenting it here)

jwwishart
Nice, I'm just getting my hands on data annotations and I think this will be helpful soon.
mare
@mare : I've just added a link to a blog entry i'm making that describes a little more about what i was doing and how to get rid of some other default validation issues (like numeric fields having another English message that I want to localize!)
jwwishart
A: 

I have RTM installed and dont have the AddImplicitRequiredAttributeForValueTypes property...

Sam
So you have the namespace required to see the DataAnnotationsModelValidatorProvider class in scope (System.Web.Mvc) and you can't see the property? Note that the property is static so don't try and instanciate an instance of DataAnnotationsModelValidatorProvider! Does that help or is it something else?
jwwishart