jquery validate always returning true
Asked Answered
H

5

11

I am using MVC4 w/JQuery and I have a form I created using the @Ajax.BeginForm. It has required fields (set on its view model). I am trying to validate the form before it is submitted back; however, it does not seem to validate.

I had a submit button originally and it was just submitting the form. I changed the submit button to a regular button and tried calling $('#formname').validate() but it always returns true (even tho required fields are not filled in). Other views seem to work fine (that are not using the Ajax.BeginForm).

I am referencing jquery, jquery-ui, jquery.validate, jquery.validate.unobtrusive, and jquery.unobtrusive-ajax.

Anyone have any ideas/suggestions what I am missing?

edit---------------------------------------------------------------------------

Below is my code (this is inside a master page that references the jquery scripts):

@model AimOnlineMRA.Models.Reports.DateRangeViewModel 

@using (Ajax.BeginForm("GetReport", "Reports", new AjaxOptions
{
    UpdateTargetId = "report_pane", HttpMethod = "Post"}, new {@id="parameterForm"}))
{
    @Html.AntiForgeryToken()

<script type="text/javascript">
    $(document).ready(function () {
        ApplyTheme();

        $('#btnYes').click(function() {
            $('#RunSpecificDateRange').val('true');

            $('#yesNo').hide();
            $('#dateRangeForm').show();
        });

        $('#btnCancel').click(function () {
            $('#report_pane').html('').hide();
        });

        $('#btnOk').click(function () {
            //if ($('#parameterForm').valid()) {
            //    alert('valid');
            //} else {
            //    alert('invalid');
            //}
        });

        $('#dateRangeForm').hide();

        $('#BeginDate').datepicker({
            showOn: 'button',
            buttonText: 'Date Picker',
            buttonImageOnly: true,
            buttonImage: '@Url.Content("~/Content/Icons/calendar-icon.png")'
        });

        $('#EndDate').datepicker({
            showOn: 'button',
            buttonText: 'Date Picker',
            buttonImageOnly: true,
            buttonImage: '@Url.Content("~/Content/Icons/calendar-icon.png")'
        });
    });
</script>

<div class="margin-auto" style="width: 400px">

    <div id="yesNo">
        <span class="bold">Do you want to run this report for a specific date range?</span> 
        <br /><br />
        @Html.Button("Yes", "btnYes")
        @Html.Button("No", "btnNo")
    </div>
    <div id="dateRangeForm">
        <span class="bold">Date Range</span> 
        <br /><br />
        <div class="left">
            <div class="left clear-both">
                @Html.LabelFor(x => x.BeginDate) <br />
                @Html.TextBoxFor(x => x.BeginDate, new {@style="vertical-align:top"})
                @Html.ValidationMessageFor(x => x.BeginDate)
            </div>
            <div class="left clear-both m-top-5">
                @Html.LabelFor(x => x.EndDate) <br />
                @Html.TextBoxFor(x => x.EndDate, new {@style="vertical-align:top"})
                @Html.ValidationMessageFor(x => x.EndDate)
            </div>
        </div>
        <div class="left m-left-10">

        </div>
        <div class="left clear-both m-top-10">
            @Html.Button("Ok", "btnOk")
            @Html.Button("Cancel", "btnCancel")
        </div>
    </div>
</div>
}

-----------------RESOLUTION-----------------------------

calling $.validator.unobtrusive.parse($('#parameterForm')); before $('#parameterForm').valid(); fixed the issue

Hippomenes answered 26/7, 2013 at 12:48 Comment(5)
Please post some relevant code, maybe use jsfiddle.netParrott
Does your model have [Required] attribute on the specified fields ? Do you create your inputs using the Razor HtmlHelpers?Caucus
Yes I do have [Required] on the vm and i did create them using the razor helper. this is one of the required fields that was output when i view it in chrome <input data-val="true" data-val-date="The field End Date must be a date." data-val-required="*Required" id="EndDate" name="EndDate" style="vertical-align:top" type="text" value="" class="hasDatepicker">Hippomenes
try $.validator.unobtrusive.parse($('#parameterForm')) before calling $('#parameterForm').valid()Caucus
Your resolution works for me too. This issue was happening on a ajax loaded form. Thanks.Messiaen
C
30

Try

$.validator.unobtrusive.parse($('#parameterForm'))

before calling

$('#parameterForm').valid()

Caucus answered 26/7, 2013 at 13:18 Comment(4)
This doesn't seem to be working for me. I am still getting a return value of true even with no data in required fields. Any idea as to why this might occur?Becoming
Weird that I have never used this and never had a problem getting unobtrusive validation to work. Today, suddenly, a single form, not unlike any other, is showing this problem. This works! I wish I understood why I only needed in this one instance. Hate mystery issues like that.Nickolenicks
The form that you are talking about, is it dynamically loaded after document load ?Caucus
In my case the problems was the form was dynamically added. If so, you need to parse the form with that function when you load the form or the view with the form as @CristiPufu suggested.Ursas
R
11

Question already has an accepted answer, but here's another possible reason for anyone that finds this in the future...

Make sure that your first validated element in the form has a name attribute, like this:

<input type=text required name='blah' />

I spent 2 hours tracking down this same issue, and I found that if the FIRST validated element in the form has a name attribute then everything works as you would expect (that is, .valid() will return false if the form is invalid). It seems to make no difference whether the other validated elements have name attributes or not.

In normal forms, you definitely need name attributes because that's what's used when the data gets submitted to the server. But in more modern environments, such as those using Knockout, there's no reason to have a name attribute on input elements, because the data-binding works to keep your data model updated.

Rosanarosane answered 14/3, 2014 at 1:45 Comment(4)
Adding 'name' attribute helped, but I was still getting validator=true (jQuery Validation Plugin - v1.13.0). So I got around this with the following code: [code]var validator = $("#login-form").validate(); validator.form(); alert("validator.numberOfInvalids() = "+validator.numberOfInvalids()); if (validator.numberOfInvalids() != 0) { alert("validation failed"); return; } alert("validation passed - continue");[/code]Swithbart
You should understand the difference between unobtrusive and normal validation.Retinue
@Dementic perhaps your comment could be a bit more useful. Could you explain, for the benefit of the rest of us plebs, what the difference is and how it would apply in this case??Rosanarosane
@MichaelBray - The "required" attribute is for non unobtrusive validation.Retinue
H
2

Did you add required to the HTML tag of the <input> or <textarea> ?

IE:

<input id="cemail" type="email" name="email" required/>
Huskamp answered 26/7, 2013 at 12:52 Comment(1)
i have the [Required] attribute on the forms viewmodel. Looking at the html output in the browser, i have the following (for one of the required fields): <input data-val="true" data-val-date="The field End Date must be a date." data-val-required="*Required" id="EndDate" name="EndDate" style="vertical-align:top" type="text" value="" class="hasDatepicker">Hippomenes
B
0

For Googlers - This can also happen when you don't have the proper Bind Attributes in your MVC route. For example, if you post a form element with a name that's not in the Include list, you may get the error.

// make sure the list matches your form elements. 
public ActionResult Edit([Bind(Include = "Username,FullName,Email")] User user)

Either make sure your form names match those in the Include list, or remove the Bind Attribute all together (if you don't mind sacrificing security).

Beriberi answered 24/1, 2019 at 16:58 Comment(0)
E
-4

I was referencing both files:

  • jquery.validate.js
  • jquery.validate.unobstrusive.js <-- remove this reference !

removing reference to jquery.validate.unobstrusive.js, fixed it for me

hope this helps somebody

Epicureanism answered 21/5, 2014 at 18:15 Comment(2)
Those scripts do not conflict at all. jquery.validate.js is required for jquery.validate.unobtrusive.js to work. You must have had that included somewhere else.Ay
You keep posting this everywhere. This is not the answer.Coffer

© 2022 - 2024 — McMap. All rights reserved.