jquery validate always returning true

前端 未结 5 1213
北荒
北荒 2020-12-31 21:16

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

相关标签:
5条回答
  • 2020-12-31 21:58

    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).

    0 讨论(0)
  • 2020-12-31 22:06

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

    IE:

    <input id="cemail" type="email" name="email" required/>
    
    0 讨论(0)
  • 2020-12-31 22:12

    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

    0 讨论(0)
  • 2020-12-31 22:16

    Try

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

    before calling

    $('#parameterForm').valid()

    0 讨论(0)
  • 2020-12-31 22:21

    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.

    0 讨论(0)
提交回复
热议问题