Im new to mvc and have several questions about asp mvc 3 validation, help regarding any of those would be apreciated:
First I have a model class that requires some fields to be present like this:
[Required(ErrorMessage = "Required field")]
public UInt16 SomeField { get; set; }
It’s working but the error message is apearing in black font (i want it red), and i think that the validation is taking plance on the server side instead of on the client, i’ve been reading some tutorials about how to make javascript validation work but it’s not working apparently:
Web.config
<appSettings>
<add key="ClientValidationEneabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Index.cshtml
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
@{ Html.EnableClientValidation(); }
That would be my second question, make it work on the client side.
And for some fields that have the Required validator and have a set of radio buttons asociated with them like this
model
[Required(ErrorMessage = "Required field")]
public UInt16 SomeField { get; set; }
view
@Html.RadioButtonFor(model => model.SomeField, 1) Label
@Html.RadioButtonFor(model => model.SomeField, 2) Label
@Html.ValidationMessageFor(model => model.SomeField)
the validation message is not showing up (even on black font) when you miss to click a radio button, how you can make it show when there are not pressed buttons.
ASP MVC 3
Razor engine
Microsoft*.jsscripts are deprecated in ASP.NET MVC 3 and should no longer be used. You can completely get rid of them. They are provided only for backwards compatibility if you are upgrading an older application. The same stands true for theHtml.EnableClientValidation();helper. They were replaced byjquery.validateplugin and the unobtrusive validation scripts.And since you have enabled unobtrusive validation in your web.config all you need in order to enable client side validation in an MVC 3 application is to include the
jquery.validate.jsandjquery.validate.unobtrusive.jsscripts, along with the version ofjquerythat you are using of course because both those scripts depend on it.Another remark about your code is the
[Required]attribute that you applied to a non-nullable type (ushort). This makes no sense because non-nullable types, by their very nature, always have value. The Required attribute should be used only on nullable types, for example:As far as the color of the validation message is concerned, both client side and server side validation uses the same HTML structure. So it’s really a matter of CSS to design the look and feel of those messages.