Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validating form in MVC3 using javascript

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.

like image 639
Santosh Avatar asked Sep 15 '25 22:09

Santosh


1 Answers

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)

like image 184
Tom Chantler Avatar answered Sep 18 '25 17:09

Tom Chantler