158

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.

Milad Rashidi
  • 1,296
  • 4
  • 22
  • 40
usr
  • 168,620
  • 35
  • 240
  • 369
  • Why not validate it manually? This plugin very useful for validate whole form, but in this case more situable validate form manually. – Anatoliy Sep 25 '09 at 19:54
  • The form ist bigger that in my example. I want it automated. – usr Sep 25 '09 at 20:15

9 Answers9

195

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

Roberto Aloi
  • 30,570
  • 21
  • 75
  • 112
130

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/

Anastasiosyal
  • 6,494
  • 6
  • 34
  • 40
31

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();
}
)
Yoosaf Abdulla
  • 3,722
  • 4
  • 31
  • 34
  • My Query if($('#someID)==='2017-4-12){ $("#myform").validate().element("#i1").valid();} else { $("#myform").validate().element("#i1").invalid();} is the code correct – srinivas gowda Apr 12 '17 at 09:57
24

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

var validator = $( "#myform" ).validate();
validator.form();
Eva M
  • 625
  • 6
  • 11
  • 8
    This doesn't answer the question, since the question is about validating only one specific field. But it's exactly what I was looking for. Thanks! – jlh Jan 28 '20 at 09:40
4

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.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
4

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();
J-S-B
  • 41
  • 1
1

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'
  });
});
LeoX
  • 117
  • 1
  • 9
0

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; }
.....
}
bherto39
  • 1,516
  • 3
  • 14
  • 29
0

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

Tobi G.
  • 1,530
  • 2
  • 13
  • 16