jQuery Validation - form.valid() always returning true

☆樱花仙子☆ 提交于 2019-12-21 11:59:07

问题


I have a situation when I try to check if a form is valid, but form.valid() always returns true. But if I try to validate the individual control, it returns false.

This is my form:

<div class="profilestagsedit">
    @using (Html.BeginForm("", "", FormMethod.Post, new { id = "tagsform" }))
    {
        @Html.ValidationMessageFor(x => x.EditTagsText)
        @Html.TextBoxFor(p => p.EditTagsText, new
           {
               @id = "txtprofileedittags"
           })
    }
</div>

This is my viewmodel:

[Required(AllowEmptyStrings = false, ErrorMessage = "Please enter at least one Tag ")]
public string EditTagsText { get; set; }

This is the jQuery code:

   $('#tagsform').removeData("validator");
   $('#tagsform').removeData("unobtrusiveValidation");
   $.validator.unobtrusive.parse('#tagsform');
   $('#tagsform').validate();

And on the save button click:

var isValid = $('#tagsform').validate().element($('#txtprofileedittags')); <-- false
$('#tagsform').valid() true <--

I would like the form.valid() return false as well, what am I doing wrong?


回答1:


You should add required to the input

<input type="text" name="name" required>

See working demo here

For unobtrusive HTML 5-compatible attributes describe the validators to be attached to the input fields data-val="true".

See more info here




回答2:


The question already has an accepted answer, but I believe that I've found more specific answer. I have found that if the FIRST validated element in the form has a 'name' tag then everything works as you would expect (that is, .valid() will return false if the form is invalid). The accepted answer conveniently included a 'name' tag and thus it worked.

In normal forms, you definitely need name tags 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' tag, because the data-binding works to keep your data model updated.




回答3:


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



来源:https://stackoverflow.com/questions/20672406/jquery-validation-form-valid-always-returning-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!