2

I would really appreciate some help with form validation in JQuery. I am a noob, so apologies in advance if this is really simple.

Basically, I want to validate a form on a questionnaire. There are two types of inputs in the form - an input, which is using JQuery Range Slider on a scale of 1 to 5, and textarea input boxes, where the user can type thoughts into.

So the validator plugin works fine and checks all the fields and then marks in red which are incomplete. My problem comes in when the user has the filled the required information in. I can get the textarea to validate and remove the red label as soon as the user focuses out of the box, but the input will not validate if it has already validated once and picked up an error.

Some of my HTML Form:

<tr>
    <td>Rate how confident you feel about your knowledge on the subject</td>
    <td class="slider-holder">
        <div class="slider num"></div>
        <input class="sliderValue validateFormClass" type="text" readonly="true" name="fb_33" required />
    </td>
</tr>
<tr>
    <td>List three important concepts or ideas that you learned in this course</td>
    <td class="slider-holder">
        <textarea name="fb_34" class="textAreaFBSurvey validateFormClass" required></textarea>
    </td>
</tr>

My JQuery Validation code:

$(document).ready(function () {
    $('.form-required').validate({
        onclick: false,
        focusInvalid: false,
        focusCleanup: true,
        errorPlacement: function (error, element) {
            $('.error-message').removeClass('hidden');
           $(element).closest('tr').addClass('error');
        },
        onfocusout: function (error, element) {
            $('textarea.valid').closest('tr').removeClass('error');
        },
        submitHandler:function (form) {
            form.submit();
        },
    });
});

Fiddle Demo

What I am trying to achieve is that should a user submit an incomplete form, the missing fields will be marked as red. As soon as that user then fills out the remaining fields, be it a textarea or an input, the 'error' classes would then be removed without having to click the submit button. This just makes it more visually appealing and easier to understand that all fields are complete.

I have tried in vain for 2 days now and not been able to figure this out, so any direction or a simple 'this is impossible' will be much appreciated.

Many thanks

5
  • 1
    The textarea is the only element you're removing the .error class from ? Commented Jan 9, 2015 at 8:27
  • $('.valid').closest('tr').removeClass('error'); Commented Jan 9, 2015 at 8:28
  • So that does help, but this is another problem - all the textareas validate, but only the first input that I click works, after that, none of the other input's validate. I'm wondering if there is a conflict possibly with Bootstrap or the Range Slider plugin. Commented Jan 9, 2015 at 8:42
  • Without seeing an example of your actual code that is testable (i.e. not just snippets), this question will be pretty difficult to answer. Especially if you believe there is a conflict with one of your resources. Improving the available code and demos in your question will help. Commented Jan 9, 2015 at 11:46
  • Your jsFiddle is no good if it's not constructed to show us anything. The input elements need to be inside of <form></form> tags and a submit button would be helpful. Your version of the validation plugin (1.7) is also too old to work with jQuery 2. jsfiddle.net/m0skkb6s Commented Jan 9, 2015 at 18:36

3 Answers 3

1

Your code is problematic...

errorPlacement: function (error, element) {
    $('.error-message').removeClass('hidden'); 
    $(element).closest('tr').addClass('error');
},
onfocusout: function (error, element) {
    $('textarea.valid').closest('tr').removeClass('error');
},
  • errorPlacement is fired upon an error and it's only used for placement of the error message, not for toggling classes.

  • onfocusout is fired whenever a field loses focus (after initial submit) and it's only used for triggering the validation. This is also not the proper place to be adding/removing classes.

The more proper options for toggling your classes are highlight and unhighlight.

Something closer to this.

highlight: function(element, errorClass, validClass) {
    $(element).closest('tr').addClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
    $(element).closest('tr').removeClass(errorClass);
},

You can use conditionals inside those functions to restrict certain actions to certain elements.


Problems with your jsFiddle demo:

  • You do not have any <form></form> tags. The jQuery Validate plugin will not work without form tags.

  • You've included version 1.7 of the jQuery Validate plugin, which is way too old to work with jQuery v2. The latest version of this plugin is 1.13.1.

  • You don't have a submit button, so there is nothing to trigger validation on the form.

  • Your text input is readonly while it's also marked as required. The user will never be able to enter data here so no need to make it required.

  • Improper usage of errorPlacement and onfocusout as per my answer above.

  • You do not need the submitHandler option when it only contains the default action. In other words, since form.submit() is what already happens by default, just leave out the submitHandler.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much for the help. With regards to the JSFiddle, I wasn't really aware that I had posted it, was a mistake on my part, apologies. I have updated my code with 'highlight' and 'unhighlight', and it is working better in its validating, however, I am still having issues with the 'live' validation on the input boxes. When I click submit, it updates the validated boxes, but only when I click submit. On the other hand, if I just click in the text area's, it removes the error class. Im beginning to believe that there may be a bug that I can't fix on my side. Many thanks for the help
0

instead of

onfocusout

use

onblur

http://www.w3schools.com/jsref/event_onblur.asp

2 Comments

Thanks. I have tried that, but it still doesn't seem to work.
0

So I finally figured out how to make this code work. Turns out the problem was not with the Validator plugin, but rather with the rangeSlider plugin. Having said that, Sparky, your advice really helped, so thanks alot for the assistance.

I have listed my final JQuery code below, both with the rangeSlider and Validator, for anyone who may have similar problems. (Note: the JSFiddle still doesn't work).

                $(document).ready(function() {
                var cellWidth = 0;
                var newWidth = 0;
                $(".radio-header").each(function() {
                    var newWidth = $(this).width();
                    if (cellWidth < newWidth )
                    {
                        cellWidth = newWidth;
                    }
                });
                $(".radio-header").width(cellWidth);

                $( ".num" ).slider({
                    range: "max",
                    min: 1,
                    max: 5,
                    value: 0,
                    slide: function( event, ui ) {
                        $(this).siblings(":text").val( ui.value );
                        $(this).closest('tr').removeClass('error');
                    }
                });
            });

            $(document).ready(function () {
                $('.form-required').validate({
                    focusInvalid: false,
                    focusCleanup: true,
                    errorClass: "hidden",
                    highlight: function(element, error, errorClass) {
                        $(element).closest('tr').addClass('error');
                        $('.error-message').removeClass('hidden');
                    },
                    unhighlight: function(element, error, errorClass) {
                        $(element).closest('tr').removeClass('error');
                    },
                });
                $.validator.addClassRules({
                    sliderValue: {
                        required: true,
                        digits: true,
                    },
                });
            });

2 Comments

What jsFiddle are you talking about because I did not give you one? I merely referenced your broken jsFiddle to point out the mistakes contained within.
Maybe that was a bit ambiguous, I was referring to my original broken JSFiddle. Apologies about the mix up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.