Manual form validation in MVC 3 and JQuery
Asked Answered
B

4

14

I want to be able to trigger form validation on the client side when the user selects the "GO" button. Currently when the "GO" button is selected it does not validate the complete form. For example, If I load the form and select the "Go" button without giving focus to the text box, nothing is validated and val.Valid() returns true. If I do enter invalid data in a text box, validation is ran for that individual item; and when I select the "GO" button, val.Valid() return false.

So what I'm trying to do, is when a user select a button or other event, I want to trigger all the forms validation.

I'm doing this in MVC 3

public class TestValidationModel
{
    [Required(ErrorMessage="UserName Is Required")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed")] 
    [StringLength(12, MinimumLength = 3)] 
    public string UserName { get; set; }

    [Required(ErrorMessage="Password Is Required")]
    [StringLength(20, MinimumLength = 3)] 
    public string Password { get; set; }

    [Required(ErrorMessage="Email Address Is Required")]
    [Display(Name = "Email Address")]
    public string EmailAddress{ get; set; }

}

<script src="/BasicMvc3Example2/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
        $("#butValidateForm").click(function(){

            var val = $('#myForm').validate()
            alert(val.valid());
        })
    });
</script>

@using (Html.BeginForm("", "", FormMethod.Post, new {id = "myForm"}))
{
    <div>
       @Html.LabelFor(m => m.UserName)
       @Html.TextBoxFor(m => m.UserName)
       @Html.ValidationMessageFor(m => m.UserName)
    </div>

    <div>
       @Html.LabelFor(m => m.Password)
       @Html.TextBoxFor(m => m.Password)
       @Html.ValidationMessageFor(m => m.Password)
    </div>

    <div>
       @Html.LabelFor(m => m.EmailAddress)
       @Html.TextBoxFor(m => m.EmailAddress)
       @Html.ValidationMessageFor(m => m.EmailAddress)
    </div>

    <button id="butValidateForm">GO</button>
    <input type="submit" id="submitForm" value="Submit" />
}

Update

I think I found the solution to my problem. See showErrors Below

   <script type="text/javascript">
        $(function () {
            $("#butValidateForm").click(function () {

                var val = $('#myForm').validate();
                val.showErrors();  //<-- Call showErrors
                alert(val.valid());
            })
        });
    </script>

This following link to the post on JQuery forms did not pertain to my problem, but I was able to find the method names I was looking for. http://plugins.jquery.com/content/jqueryvalidate-showerrors-issue-form-wizard

If someone has a better answer, please provide feedback.


Update

The previous code somewhat works in Firefox, but not at all in IE. I did the following and it works now in Firefox but still not in ID

    $(function () {
        $("#myForm").submit(function (e) {
            var val = $('#myForm').validate(); //<--added the semi-colon
            val.showErrors();
            alert(val.valid());


            e.preventDefault();
        });
    });


//            $("#butValidateForm").click(function () {
//                var val = $('#myForm').validate()
//                val.showErrors();
//                alert(val.valid());
//            })
    });

Thanks for Using jQuery To Hijack ASP.NET MVC Form Posts for pointing me in the correct direction. But still not perfect

Bartie answered 19/2, 2011 at 23:59 Comment(0)
M
10

I don't know if this is the best/most efficient way, but I do it by validating each element individually in my own function.

jQuery(document).ready(function () {

    $("#butValidateForm").button().click(function () { return IsMyFormValid(); });
    $('#myForm').validate();

}

function IsMyFormValid() {

    var isValid = false;

    isValid = $('#myForm').validate().element($('#UserName '));
    isValid = ($('#myForm').validate().element($('#Password '))) ? isValid : false;
    isValid = ($('#myForm').validate().element($('#EmailAddress'))) ? isValid : false;

    return isValid;
}

It would be great to let it validate automagically, but I always seem to run into some weird business logic rule that doesn't get caught by the generic validation methods. Doing it this way lets me control all of the validation the way I want to, but relying on built in validation most of the time.

Madrid answered 20/2, 2011 at 6:49 Comment(3)
This is a better way of doing isMyformValid() using .each() method >>>>>>>>>> $('#myForm').validate().elements().each(function () { $('#myForm').validate().element(this); });Media
In the context of this situation, I'd argue the .each method is a worse way to implement IsMyFormValid(). The IsMyFormValid() method exists to explicitly define what elements are validated. The best solution to validate every element would be to completely remove IsMyFormValid() and the following call: ("#butValidateForm").button().click(function () { return IsMyFormValid(); }); since this is what the validation plugin does by default.Madrid
aahaa! I thought you wanted to validate every field.Media
C
8
<script type="text/javascript">
    $(function () {
        $("#butValidateForm").click(function (event) {

            var isValid = $('#myForm').valid();
            if(isValid)
            {
               //do something before submit the form
               $('#myForm').submit();
            }else{
               alert('validation failed'); 
            }
            event.preventDefault();
        })
    });
</script>
Cotton answered 25/6, 2012 at 3:54 Comment(0)
I
3

Not sure if you figured this out yet, but I ran into the same thing in IE with $("#myForm").submit. Use live:

$("#myForm").live('submit', function (e) {
    var val = $('#myForm').validate(); //<--added the semi-colon
    val.showErrors();
    alert(val.valid());


    e.preventDefault();
});
Injure answered 7/3, 2011 at 21:29 Comment(0)
P
0

Its not working in IE because you are missing a semi-colon:

var val = $('#myForm').validate()
Phenanthrene answered 20/2, 2011 at 6:47 Comment(2)
Thanks for the suggestion. I added the semi-colon, but still doesn't work in IE.Bartie
Good question. The Event for that I attached to the form submit never gets called. The alert is never displayed.Bartie

© 2022 - 2024 — McMap. All rights reserved.