[javascript] How to manually trigger validation with jQuery validate?

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.

This question is related to javascript jquery html jquery-validate

The answer is


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();
}
)

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/


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

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

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


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; }
.....
}

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.

_x000D_
_x000D_
//1) Enable jQuery validation_x000D_
var validator = $('#myForm').validate();_x000D_
_x000D_
$('#myButton').click(function(){_x000D_
  //my own validation logic here_x000D_
  //....._x000D_
  //2) when validation failed, show the error message manually_x000D_
  validator.showErrors({_x000D_
    'myField': 'my custom error message'_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_


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.

3) Use the variable/global and call form.

var bIsValid = oValidator.form();

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery-validate

Phone Number Validation MVC Jquery Validate custom error message location Jquery validation plugin - TypeError: $(...).validate is not a function JQuery Validate input file type jquery to validate phone number Bootstrap with jQuery Validation Plugin jQuery Validation plugin: validate check box jQuery select box validation Confirm Password with jQuery Validate MVC 4 client side validation not working