0

I am pretty new to asp.net MVC. I have a problem in attaching client side validation errors to validation summary list in MVC. On the client side submit click function, the validation-summary-errors div is always empty even if there are validation errors in form.

Let me explain in detail with code snippet.The snippet that I have provided is my sample application.

I have enabled clientside validation in my application trhough web.config and included the default jquery validations library in my layout page.

@Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")

MVC View

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword)
            </li>
        </ol>
        <input type="submit" value="Register" id="btnSubmit" />
    </fieldset>
}

View Model is below

public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

Script file that I have used is below.

<script type="text/javascript">
    $(function () {
        $("#btnSubmit").click(function (e) {
            e.preventDefault();            
            var errorSummary = $('.validation-summary-errors');
            if (errorSummary.length == 0) {
                $('#listError').remove();
                $('<div class="validation-summary-errors"></div>').insertAfter($('.validation-summary-valid'));
                $(".validation-summary-errors").append("<ul id='listError'><li>You cannot enter more than 20 characters.</li></ul>");
            }
            else if (errorSummary.length == 1) {
                $('#listError').remove();
                $(".validation-summary-errors").append("<ul id='listError'><li>You cannot enter more than 20 characters.</li></ul>");
            }
            return false;
        });

    });

</script>

When I don't have jquery submit click function everything works fine as expected. Model valiadtions are fired in client side on submit click.

In addition to model validations I also have some jquery client side validations that need to be appended to existing list of validation summary. But "validation-summary-errors" div is always empty in submit click function. So every time the $('.validation-summary-errors').length is 0.

Can someone help me understand where am I going wrong?

Updated code

$(function () {
    $("#btnSubmit").click(function (e) {

        var IsValid = validateForms();
        if (!IsValid) {
            e.preventDefault();
        }
    });
});

function validateForms() {

    var blnValid = false;
    var valMsg = ValidateDynamicControls();

    if ($('#MemberForm').valid()) {
        $(".validation-summary-errors").empty();
        blnValid = true;
    }
    if (valMsg != '') {

        blnValid = false;
        var errorSummary = $('.validation-summary-errors')
        if (errorSummary.length == 1 && errorSummary[0].innerHTML != '' &&    errorSummary[0].innerHTML != undefined) {
            $(".validation-summary-errors ul").append(valMsg);
        } else {

            $('#listError').remove();
            $('<div class="validation-summary-errors"></div>').insertAfter($('.validation-summary-valid'));
            $(".validation-summary-errors").append("<ul id='listError'>" + valMsg + "</ul>");
        }
    }

    return blnValid;
}

function ValidateDynamicControls() {
    var strAliasValMsg = 'The string is not valid.';

    return strAliasValMsg;
}
BrianS
  • 13,284
  • 15
  • 62
  • 125
user1081802
  • 47
  • 1
  • 1
  • 6

1 Answers1

3

I'd be willing to bet you that your e.preventDefault(); and return false; are the roots of your problems since they are suppressing propagation of the event. The jquery validation library never knows that the form has been submitted because you're killing the event before it can be processed.

Also, you don't need both preventDefault and return false. In fact, you don't need either one all the time- in your case it's probably going to be more appropriate to call preventDefault and do it conditionally.

But really, that's probably not sufficient either. If the included validators are not sufficient, what you really should be doing is implementing a CustomValidationAttribute along with the IClientValidatable interface. That will make everything play nice both client and server side. You can find lots of examples with a Google or Stackoverflow search, like this one, for example. Alternatively, you can implement a Remote Validator if the first solution isn't up to the task.

Community
  • 1
  • 1
joelmdev
  • 11,083
  • 10
  • 65
  • 89
  • Thank u for your response. Will try this one and will let u know how it goes. – user1081802 Nov 27 '13 at 04:01
  • I commented the e.preventdefault and return false in my function. That helped me solve one issue. The model validations are now showing up in the screen along with script validation. But as I said earlier, the "validation-summary-errors" class is empty after submit click. So I could see 2 different divs of validation errors.Javascript validations are not appedning to the existing validation error. – user1081802 Nov 27 '13 at 14:49
  • I'm not really sure what additional validation you're trying to achieve. did you look into implementing a CustomValidationAttribute with IClientValidatable? That would eliminate any hacking you're having to do assuming it will fit your needs. – joelmdev Nov 27 '13 at 15:09
  • I have to dynamically add html input file object to existing div, onclick of Add attachments anchor link. Since these are dynamically added objects I need to do client side validations. I will also try customcaliadtionAttribute and update you. – user1081802 Nov 27 '13 at 15:32
  • As you said e.PreventDefault() was the culprit in this case. Thanks Joelmdev for guiding me in right direction.I have updated my question with answer that I derived. – user1081802 Dec 03 '13 at 22:44