Santosh
Santosh

Reputation: 2515

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.

Upvotes: 4

Views: 12887

Answers (3)

Berker Y&#252;ceer
Berker Y&#252;ceer

Reputation: 7335

Now <%= Html.TextBoxFor(model => model.Name)%> is the key here u should give an ID to each of your elements that you want to use validation on..

so its gonna look like;

<%= Html.TextBoxFor(model => model.Name,new { id="ClientNameTxt"})%>

if you already defined some scripts (.js files) and want to implement to this view then use

<script src="@Url.Content("~/Scripts/yourjsfile.js")" type="text/javascript"></script>

and use ur functions to validate or else write new script

<script type="text/javascript">
    $(document).ready(function () {
        var frm = $("#formname");
        frm.validate();
    });

    $('#formname').Submit(function (event) {
        /* Call ur form with the id you have given */
        var f = $("#formname");

        if (f.valid()) {  /* When the form is valid */

        } else {  /* When the form is not valid */
            event.preventDefault(); /* Prevent from submitting the form */
            $("#ClientNameTxt").highlight(); /* Do some validation stuff on ur validation required element */
        }
    });
</script>

at the end it will look like;

                 <!--Your form name, Controller name-->         
@using (Html.BeginForm("Formname", "ControllerName", FormMethod.Post,new { id="Formname", onkeypress="return event.keyCode != 13;"}))
{
    <p> 
        <label for="ClientName">ClientName:</label> <!--Give an ID to your element-->
        <%= Html.TextBoxFor(model => model.Name, new { id="ClientNameTxt" })%>
    </p>
}

<script type="text/javascript">
    $(document).ready(function () {
        var frm = $("#formname");
        frm.validate();
    });

    $('#formname').Submit(function (event) {
        /* Call ur form with the id you have given */
        var f = $("#formname");

        if (f.valid()) {  /* When the form is valid */

        } else {   /* When the form is not valid */
            event.preventDefault(); /* Prevent from submitting the form */
            $("#ClientNameTxt").highlight(); /* Do some validation stuff on ur validation required element */
            $("#Formname").append('<ul><li> Fill the empty areas and try again. <li><ul>');
            /* This is the worst i can do. Just to let you understand it easly. */
        }
    });
</script>

if u still have problems with this issue! i guess ur solution is at training your self with the --> jquery

Upvotes: 1

Tom Chantler
Tom Chantler

Reputation: 14951

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)

Upvotes: 7

Deepakmahajan
Deepakmahajan

Reputation: 866

Try this code.it work on my side you should try:

 <form id="formname" post="" action="">
<ul>
<li>
 <input type="text" name="TimeArrived" id="TimeArrived" class="required" /></li>
 <li><input type="text" name="Name" id="Name" class="required"   />
</li>
 <li>
    <input type="button" name="Save" value="Save" onclick="return Submit();" /></li>
   </ul>
</form>

 $(document).ready(function () {
        var frm = $("#formname");
        frm.validate();
    });

 function Submit() {
  var f = $("#formname");

 if (f.valid())
{
}
}

Upvotes: 2

Related Questions