I just need example for one validation. For remaining I will do. Let's say I have an input of type text:
<p>
<label for="ClientName">ClientName:</label> <%= Html.TextBoxFor(model => model.Name)%>
</p>
Here I want to validate textbox for required field. I want this required field validation function in JavaScript and I want to use this script in the view.
Have you considered using unobtrusive validation?
You say you are using MVC3 (although not the Razor view engine apparently).
With your code like this: <p><label for="ClientName">ClientName:</label> <%= Html.TextBoxFor(model => model.Name)%></p>
which could be written as
<p>@Html.LabelFor(model=>model.Name) @Html.TextBoxFor(model => model.Name) </p>
in Razor syntax.
If you put this in your web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
and then decorate the property in your model with something like this data annotation:
[Display(Name = "Name")]
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
Then by adding the following into your _Layout.cshtml
file you will get unobtrusive validation to work:
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Then you could add this somewhere on the page (where you want the validation message to be shown): @Html.ValidationMessageFor(model=>model.Name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With