Link to home
Start Free TrialLog in
Avatar of mikha
mikhaFlag for United States of America

asked on

custom jquery validation method

I'm using jquery validation plugin for my client side validation on my site. I had to come up with a custom method, to do group validation for the input fields. for example - name and address fields are grouped as contact fields and either user can enter all of them or skip all of them.
Looking at the Jquery validation plugin, it has in built function that does group validation, look at  two functions at the following link by jquery contributors -
https://github.com/jzaefferer/jquery-validation/commit/e5207d63a831fdfa30ea6927906288ae60336c76#diff-82185dc776c598c0eaf19f2c0f743011

Question - currently, when these functions are used - when you start typing the first field in the group, all the other fields in the group will be highlighted and will show error that all fields are required. the error messages under each field not be resolved until all the fields in the group are either entered or cleared.
a better user experience would be, as user starts typing in, the error message for that field disappears.

I am still learning jquery, so looking for help - creating a custom function to validate group of fields and displaying error for only fields that are empty.
Avatar of leakim971
leakim971
Flag of Guadeloupe image

The shorcut it to not use the jQuery.validation for this group. You can still use it for the other fields of your form (password, phone,...)
The following fill your requirements, we use the same "error" class like the jQuery validation plugin

jQuery(function($) {     
     var number_of_fields_required_by_group_1_min = 1000000; // mean all
     $(".group_of_fields_1").blur(function() {
            $(".group_of_fields_1").each(function() {
                 if($(this).val().length)
                     $(this).addClass("filled");
                 else
                     $(this).removeClass("filled");
            });
            var err = $(".group_of_fields_1.filled").length < number_of_fields_required_by_group_1_min;
            if(err)
                $(".group_of_fields_1").not(".filled").addClass("error");
            else
                $(".group_of_fields_1").removeClass("error");
     })
     .on("paste keyup", function() {
           if($(this).val().length)
               $(this).removeClass("error");
     });
});

Open in new window

why ? because the jQuery validation plugin work on blur, it do its validation when the field loose focus.
Avatar of mikha

ASKER

Thanks leakim971 for your suggestion and help. To test your sample, i assigned "group_of_fields_1" to all the required fields in the class and also set the count variable - > number_of_fields_required_by_group_1_min to all required.


1. after the page loads, if i start typing in a field and move to another filed it will highlighted all the fields . Since i already input value in the first field , can it detect that the first field is already filled and not highlight that field? from the code, it looks like the code fires once, we move from the field , on the Keyup event. can we fire this function as user starts to type in the first field.

2. Second error that i get is , when i hit submit button on the page, after filling in all the fields, all the fields are highlighted and marked as require, how to get rid of this?

3. after second step , where all fields are entered, if i tab from field 1 to field 2, the field 2 is still highlighted , but when i tab over the highlight is gone. since all fields are filled at this stage, the fields should be highlighted and marked as error.

4. one last question, .on("paste keyup", function() .. does this get called multiple of times when user inputs a field. should it be called only once?
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mikha

ASKER

Thanks for the response again. this is awesome.

1. I noticed this part of the code (see below) . I don't have this. The way i'm using the jquery validation plugin is form my project is , i simply set data-rule annotations and the rule fires up on the client side ( i think i can call it unobtrusive). so where would i put the following code.

2. also, i believe , it would be a minor change , to make it such that either all fields are required in the group or none are required.

 
 $("#myform").submit(function(evt) {
     	evt.preventDefault(); // remove this in your cas
      if($("input.error").length) {
	     	evt.preventDefault();
				alert("form bad");
      }
      else {
				alert("form ok");
      }
     });

Open in new window

1 - put it just after you current javascript
DON't MIX jQuery validation with the code, I mean don't try to validate phone number with jQuery validation and at the same time use the code.
Both will interferate with the other and, personnaly, I don't want to know the result if it work or not.
If jquery validation don't fill your needs, just go to another validator plugin, for example (random one) : https://github.com/mustardamus/ketchup-plugin

3 - Please use code snippet
4 - let see if the current code as it is provided run on your side before trying to implement new requirements :D
Avatar of mikha

ASKER

Thanks again.
1.  To clarify my earlier question, I wanted to know if the sample code you have provided, could be added as a custom method in jquery validation plugin.
This is what I had done, and i didn't know how to implement or where to put the last section of the code, i mentioned earlier. in the custom methods in the jquery plugin simply returns true/false. this return value determines whether or not there is a error on the field.

I am researching more on this, but let me know if you have any more thoughts on this.

your sample code works by itself, when it is on the page itself. I was trying to see if i can put it as custom method and use it from other pages as well.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mikha

ASKER

thanks again. help me out with the concept a little bit as well then.

so sample code provided, fires up when the field loses focus ( i.e on blur ) and also on keyup event right.
and you are saying the jquery validation plugin methods fires up only on blur event?

just trying to understand the concept. if you could elaborate on how both works?
Avatar of mikha

ASKER

also, one more question , i made a small change in the sample you provided and everything works except, "added line 1" and 2 below works
but "added line 3" doesn't work. wasn't sure i can actually do what i'm doing in "added line 3". any ideas?

            if(err){
                $(".group_of_fields_1").not(".filled").addClass("error");
                $(".group_of_fields_1").not(".filled").closest('div').addClass('has-error');  //added line 1 
           }
            else {
                $(".group_of_fields_1").removeClass("error");
                $(".group_of_fields_1").not(".filled").closest('div').removeClass('has-error');   //added line 2 
           }
     })
     .on("paste keyup", function() {
           if($(this).val().length){
               $(this).removeClass("error");
              $(this).closest('div').removeClass('has-error');   //added line 3 
           }

Open in new window

just trying to understand the concept. if you could elaborate on how both works?

sorry... I don't see any best way to explain what I mean.
maybe your understanding of the blur event : https://developer.mozilla.org/en-US/docs/Web/Events/blur
or keyup : https://developer.mozilla.org/en-US/docs/Web/Events/keyup

second question :
if you're new to jQuery don't use chaining
could you setup a jsfiddle like me or share your page?