Search code examples
jqueryjquery-validateunobtrusive-validation

jQuery Validation - form.valid() always returning true


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?


Solution

  • 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