0

What I have set up is a big form with two main pieces. The first piece the user is filling out some basic info. The second piece the user is adding some 'sizing' options, which there could be multiples of. The sizing info is filled out in a panel and then 'saved', cloning the form elsewhere and then wiping the panel for another size to be added. When this 'save' takes place, I fire validation for only that portion of the form.

    $.validator.addMethod("pageRequired", function(value, element) {
        if (valid_distributions > 0) {
            $('#distributor-select').prop('required', false)
        }
        if (current_page == 1) {
            return this.optional(element);
        }else if (current_page == 2) {
            return !this.optional(element);
        } else {
        return "dependency-mismatch";
        }
    }, $.validator.messages.required)

This chunk is what switched the requirement of the first half of the form. Basically, I am getting some glitchy behavior where sometimes I can validate just the bottom of the form, but othertimes Jquery is being told to validate the whole form when saving just the bottom.

I know my condition for the elements being required or not is firing, yet still they are being required.

    var v = $("#beer-create-form").validate({
        debug: true,
        rules: {
                'keg_sizes[]': {
                        required: true
                }
        },
        messages: {
            'keg_sizes[]': 'Choose at least one keg size'
        },

        errorClass: "error",
        errorPlacement: function (error, element) {
            if (element.hasClass('kegsize-toggle')){
                error.insertAfter(element.parents().find('.distributor-name'));
            }else if (element.hasClass('price')) {
                console.log('price');
            }
        },
        highlight: function(element, errorClass) {
            $(element).addClass(errorClass);
        },
        unhighlight: function(element, errorClass) {
            $(element).removeClass(errorClass);
        }
    });

    $(document).on('click', '.save-listing', function(e) {
        current_page = 1;
        if (v.form()) {             // if the form is valid, proceed to:
            saveBeerPanel();        //clones the panel being filled out with all the info
            wipeBeerPanel();        // clears all the info previously filled out so a new listing can be added
            valid_distributions += 1  // keeps track that there is at least one valid distribution
        }
        e.preventDefault();
    });

I tried changing the 'required' switch with this code:

    if (current_page == 1) {
        console.log('top is optional');
        return $(element).prop('required', false)
    }else if (current_page == 2) {
        return $(element).prop('required', true)
    } else {
    return "dependency-mismatch";
    }

... but that doesn't seem to help.

Why are those elements not being changed to optional or not?

Working fiddle demonstrates how the form should work: http://jsfiddle.net/hodale/0c41465t/

Also, here is the demo I was using for inspiration: http://jsfiddle.net/hodale/aqpyykt0/

Sparky
  • 98,165
  • 25
  • 199
  • 285
hodale
  • 717
  • 1
  • 6
  • 13

1 Answers1

1

Why are those elements not being changed to optional or not?

Because .addMethod() and this.optional(element) are not supposed to change anything.

The .addMethod() method is only for creating/evaluating a new custom rule.

And this.optional(element) within the .addMethod() method is simply used to help determine if an empty field should be ignored by this custom rule.

this.optional(element) only returns a boolean...

  • true if the element is "not required"
  • false if the element is "required"

The entire premise of the "pageRequired" method created with .addMethod() makes no sense and should be removed.

To toggle the required rule on a particular element, you can do one of the following...

  1. Toggle the required class on the element(s).

  2. Toggle the HTML 5 attribute, required="required".

  3. Set and remove the required rule using the .rules() method...

    $('#myfield').rules('add', {  // add rules
        required: true
    });
    
    $('#myfield').rules('remove', 'required'); // remove rules
    

    If you select multiple fields at once, you must use a jQuery .each()....

    $('.myfields').each(function() {  // add rules to multiple field at once
        $(this).rules('add', {
            required: true
        });
    }); 
    

I suggest that you review the documentation: jqueryvalidation.org

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • I will try adding and removing the rules as necessary using .rules(). The what do you make of [this demo](http://jsfiddle.net/hodale/aqpyykt0/) which was lifted from the jqeuryvalidation site? That's where I got the idea to use addMethod(). It seems like their premise was to create and maintatin the custom rule as the user navigated through the three page form. – hodale Mar 30 '15 at 21:44
  • @hodale, again, in the demo you reference, `return !this.optional(element);` is returning a boolean based on whether the field is ***already*** required... it is not "setting" it as "required". I've also never examined that demo closely so I cannot comment about why they chose to do it like that. There are lots of ways to do a stepped form. I prefer to use a different `
    ` for each step... it makes validation much easier.
    – Sparky Mar 30 '15 at 22:35
  • That helps a lot, splitting in two forms is the way to go... not sure why I didn't do that to begin with! – hodale Mar 30 '15 at 22:57
  • Yes, multiple forms makes things a lot easier to maintain and control. Please don't forget to "accept" my answer. Thanks. – Sparky Mar 31 '15 at 00:12