How to manually trigger validation with jQuery validate?

JavascriptJqueryHtmlJquery Validate

Javascript Problem Overview


I want to manually trigger validation including showing error messages with jQuery Validate.

The scenario I am trying to accomplish is a form like this:

<form>
 <input id=i1> <button id=b1>
 <input id=i2> <button id=b2>
</form>

When clicking b1, only i1 should be validated. hen clicking b2, only i2 should be validated. However all fields must be posted. How can I do this? I thought about handling the click event for b1/b2 and manually validating a part of the form.

Javascript Solutions


Solution 1 - Javascript

That library seems to allow validation for single elements. Just associate a click event to your button and try the following:

$("#myform").validate().element("#i1");

Examples here:

https://jqueryvalidation.org/Validator.element

Solution 2 - Javascript

Or one can simply use: $('#myElem').valid()

if ($('#myElem').valid()){
   // will also trigger unobtrusive validation only for this element if in place 
   // add your extra logic here to execute only when element is valid
}

Note that validate() needs to be called on the form before checking it using this method.

Documentation link: https://jqueryvalidation.org/valid/

Solution 3 - Javascript

My approach was as below. Now I just wanted my form to be validated when one specific checkbox was clicked/changed:

$('#myForm input:checkbox[name=yourChkBxName]').click(
 function(e){
  $("#myForm").valid();
}
)

Solution 4 - Javascript

As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()

var validator = $( "#myform" ).validate();
validator.form();

Solution 5 - Javascript

There is an undocumented method as of version 1.14

validator.checkForm()

This method silently validate for return true/false. It doesn't trigger error messages.

Solution 6 - Javascript

Eva M from above, almost had the answer as posted above (Thanks Eva M!):

var validator = $( "#myform" ).validate();
validator.form();

This is almost the answer, but it causes problems, in even the most up to date jquery validation plugin as of 13 DEC 2018. The problem is that if one directly copies that sample, and EVER calls ".validate()" more than once, the focus/key processing of the validation can get broken, and the validation may not show errors properly.

Here is how to use Eva M's answer, and ensure those focus/key/error-hiding issues do not occur:

  1. Save your validator to a variable/global.

    var oValidator = $("#myform").validate();

  2. DO NOT call $("#myform").validate() EVER again.

If you call $("#myform").validate() more than once, it may cause focus/key/error-hiding issues.

  1. Use the variable/global and call form.

    var bIsValid = oValidator.form();

Solution 7 - Javascript

In my similar case, I had my own validation logic and just wanted to use jQuery validation to show the message. This was what I did.

//1) Enable jQuery validation
var validator = $('#myForm').validate();

$('#myButton').click(function(){
  //my own validation logic here
  //.....
  //2) when validation failed, show the error message manually
  validator.showErrors({
    'myField': 'my custom error message'
  });
});

Solution 8 - Javascript

i tried it worked tnx @Anastasiosyal i want to share it on this thread.

I'm not positive how the input fields did not trigger when I emptied the fields. But I managed to trigger each required field individually using:

$(".setting-p input").bind("change", function () {
        //Seven.NetOps.validateSettings(Seven.NetOps.saveSettings);
        /*$.validator.unobtrusive.parse($('#saveForm'));*/
        $('#NodeZoomLevel').valid();
        $('#ZoomLevel').valid();
        $('#CenterLatitude').valid();
        $('#CenterLongitude').valid();
        $('#NodeIconSize').valid();
        $('#SaveDashboard').valid();
        $('#AutoRefresh').valid();
    });

here's my view

@using (Html.BeginForm("SaveSettings", "Settings", FormMethod.Post, new {id = "saveForm"}))
{
    <div id="sevenRightBody">
        <div id="mapMenuitemPanel" class="setingsPanelStyle" style="display: block;">
            <div class="defaultpanelTitleStyle">Map Settings</div>
            Customize the map view upon initial navigation to the map view page.
            <p class="setting-p">@Html.LabelFor(x => x.NodeZoomLevel)</p>
            <p class="setting-p">@Html.EditorFor(x => x.NodeZoomLevel) @Html.ValidationMessageFor(x => x.NodeZoomLevel)</p>
            <p class="setting-p">@Html.LabelFor(x => x.ZoomLevel)</p>
            <p class="setting-p">@Html.EditorFor(x => x.ZoomLevel) @Html.ValidationMessageFor(x => x.ZoomLevel)</p>
            <p class="setting-p">@Html.LabelFor(x => x.CenterLatitude)</p>
            <p class="setting-p">@Html.EditorFor(x => x.CenterLatitude) @Html.ValidationMessageFor(x => x.CenterLatitude)</p>
            <p class="setting-p">@Html.LabelFor(x => x.CenterLongitude)</p>
            <p class="setting-p">@Html.EditorFor(x => x.CenterLongitude) @Html.ValidationMessageFor(x => x.CenterLongitude)</p>
            <p class="setting-p">@Html.LabelFor(x => x.NodeIconSize)</p>
            <p class="setting-p">@Html.SliderSelectFor(x => x.NodeIconSize) @Html.ValidationMessageFor(x => x.NodeIconSize)</p>
        </div>

and my Entity

   public class UserSetting : IEquatable<UserSetting>
    {
        [Required(ErrorMessage = "Missing Node Zoom Level.")]
        [Range(200, 10000000, ErrorMessage = "Node Zoom Level must be between {1} and {2}.")]
        [DefaultValue(100000)]
        [Display(Name = "Node Zoom Level")]
        public double NodeZoomLevel { get; set; }

        [Required(ErrorMessage = "Missing Zoom Level.")]
        [Range(200, 10000000, ErrorMessage = "Zoom Level must be between {1} and {2}.")]
        [DefaultValue(1000000)]
        [Display(Name = "Zoom Level")]
        public double ZoomLevel { get; set; }

        [Range(-90, 90, ErrorMessage = "Latitude degrees must be between {1} and {2}.")]
        [Required(ErrorMessage = "Missing Latitude.")]
        [DefaultValue(-200)]
        [Display(Name = "Latitude")]
        public double CenterLatitude { get; set; }

        [Range(-180, 180, ErrorMessage = "Longitude degrees must be between {1} and {2}.")]
        [Required(ErrorMessage = "Missing Longitude.")]
        [DefaultValue(-200)]
        [Display(Name = "Longitude")]
        public double CenterLongitude { get; set; }

        [Display(Name = "Save Dashboard")]
        public bool SaveDashboard { get; set; }
.....
}

Solution 9 - Javascript

There is a good way if you use validate() with parameters on a form and want to validate one field of your form manually afterwards:

var validationManager = $('.myForm').validate(myParameters);
...
validationManager.element($(this));

Documentation: Validator.element()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionusrView Question on Stackoverflow
Solution 1 - JavascriptRoberto AloiView Answer on Stackoverflow
Solution 2 - JavascriptAnastasiosyalView Answer on Stackoverflow
Solution 3 - JavascriptYoosaf AbdullaView Answer on Stackoverflow
Solution 4 - JavascriptEva MView Answer on Stackoverflow
Solution 5 - Javascriptuser5936891View Answer on Stackoverflow
Solution 6 - JavascriptJ-S-BView Answer on Stackoverflow
Solution 7 - JavascriptLeoXView Answer on Stackoverflow
Solution 8 - Javascriptbherto39View Answer on Stackoverflow
Solution 9 - JavascriptTobi G.View Answer on Stackoverflow