KDee
KDee

Reputation: 684

Validate.unobtrusive and validate jQuery libraries

I am building an MVC 3 application which uses the standard Model validation attributes for basic client and server validation. I however also have a form which is in the header and uses the jQuery validate plugin to perform client validation.

When I add the unobtrusive library to the project the header form which uses the validate plugin fails to run and keeps posting. When the unobtrusive library is not included the header validates fine but then the Model validation stops.

Any idea what I am doing wrong?

Edit

Basically i have a login form in the header. I also have a login page that also allows login. The login page is tied to a Model but the form in the header is not, it's just html. Both forms call the same Controller/Action via jQuery .ajax.

I have lost the ability to use the .ajax method which just doesnt seem to get called since I included the unobtrusive library.

I got the code you included to work, but then I still cant post or perform an action after validation is complete.

My header form is:

<form id="frmHeaderLogin" action="">
<table id="LoginBox" title="Login">
    <tr>
        <td>UserName</td>
        <td><input type="text" id="Username" name="Username" /></td>
    </tr>
    <tr>
        <td>Password</td>
        <td><input type="password" id="Password" name="Password" /></td>
    </tr>
    <tr>
    <td colspan="2"><input type="submit" value="Login" id="btnHeaderLogin" name="btnHeaderLogin" /></td>
    </tr>
</table>
</form>

I have a click event for the submit button which would validate the client input and then submits this to the server after creating a JSON object as the data parameter. The response from the server is also a JSON object. This form is in a layout file as it's going to be on every page.

The main login page/view has a simple form as below:

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "MainLoginForm" }))
{
<div>
    <fieldset>
       <p style="color:Red;font-size:medium">@ViewData["Message"]</p>
        <legend>Login</legend>
        <div class="editor-label">
        @Html.LabelFor(m => m.UserName, "EmailId")
        </div>
        <div class="editor-field">
        @Html.TextBoxFor(m => m.UserName)
        @Html.ValidationMessageFor(m => m.UserName)
        </div>
        <div class="editor-label">
        @Html.LabelFor(m => m.Password, "Password")  
        </div>
        <div class="editor-field">         
        @Html.PasswordFor(m => m.Password)
        @Html.ValidationMessageFor(m => m.Password)
        </div>
        <p>
        <input type="submit" id="btnMainLogin" value="Login" />
        </p>
     </fieldset>
</div>
}

This also has a jQuery click event which fires the .ajax method and posts a JSON object to the server as above. Both instances return a JSON object.

I suppose at this point the question could be, can I use the same model for the header login which is in a layout file which would allow me to make use of the client and server validation?

The following is an example of the submitHandler that I was using after the validation passed (using jquery.validate)

    $("#formname").validate( {
     // .....
         // .....
         submitHandler: function () {
            var JSONData = new Object();
            $(':text, :password', $("table[id$='LoginBox']")).each(function () {
                JSONData[$(this).attr("id")] = $(this).val();
            });

            $.ajax({
                type: "POST",
                url: "/Controller/Action",
                data: "{'Login': '" + JSON.stringify(JSONData) + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    var response = $.parseJSON(result);
                    alert("Header Login Success!");
                },
                error: function (xhr, status, error) {
                    alert(xhr.statusText + " - ReadyState:" + xhr.readyState + "\n" + "Status: " + xhr.status);
                }
            });
         }
    )};

Upvotes: 4

Views: 4247

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

If you want to mix Microsoft unobtrusive validation script with custom jquery validate rules that you have written in the same page you will need to add the jquery validate rules to existing form elements. Let's take an example:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }

    public string Bar { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('#Bar').rules('add', {
            required: true,
            messages: {
                required: 'Bar is required'
            }
        });
    });
</script>

@using (Html.BeginForm())
{
    <div>
        @Html.EditorFor(x => x.Foo)
        @Html.ValidationMessageFor(x => x.Foo)
    </div>

    <div>
        @Html.EditorFor(x => x.Bar)
        @Html.ValidationMessageFor(x => x.Bar)
    </div>

    <button type="submit">OK</button>
}

Notice how the Required attribute on the Foo field makes it required and we have defined a custom jquery validate rule for the Bar field.

And here's the result when the form is submitted and the 2 fields are left empty:

enter image description here

You could of course define any number of custom rules on any field.

Upvotes: 6

Related Questions