Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to require only one of a group of fields with Parsley

Tags:

parsley.js

I am using Parsley.js for validating a form submission on a project. One of my needs is to have Parsley require that at least one of three fields have data in them, and only fail validation if none of the three fields has data.

I am not sure from the documentation, how to accomplish this. I already have Parsley validation working on the rest of the form.

like image 368
NilsonCain Avatar asked Nov 11 '22 02:11

NilsonCain


1 Answers

You can do that with a custom validator like so

var CheckReccursion = 0;
    window.Parsley.addValidator('min3', {
        validateString: function (value, requirement, instance) {
            var notice =$('#notice').html(' ');

            var group = $(requirement);//a class

            var FieldsEmpty = 0;
            var FieldsNotEmpty = 0;
            var count = 0

            group.each(function () {

                var _val = $(this).val()
                var length = _val.length

                if (length > 0) {
                    FieldsNotEmpty++;
                }
                else {
                    FieldsEmpty++;
                }
                count++;
            })

            var isValid = (FieldsNotEmpty >=1)
            //recursively execute
            group.each(function (index) {
                if (CheckReccursion === index) {
                    CheckReccursion++;
                    $(this).parsley().validate();
                    CheckReccursion = 0;
                }
            })
            return isValid;
        }
    });

$(function () {
    var ok=false;
    var notice =$('#notice');

    $('#form1').parsley().on('form:validated', function(formInstance) {
        ok = formInstance.isValid({force: true});
    })
    .on('form:submit', function() {
        if(!ok){
            notice.html('Please fill at least 1 field');
            return false;
        }
        else{
            notice.html('okay');
            return false;//change to true to submit form here

        }
    });
});

then add parsley attributes to the group of fields like so:

<form id="form1" data-parsley-validate="true">
    <input type="text" name="field1"

    data-parsley-min3 = ".group1"
    data-parsley-min3-message = "At least 1 must be filled"
    class="group1">



    <input type="text" name="field2"

    data-parsley-min3 = ".group1"
    data-parsley-min3-message = "At least 1 must be filled"
    class="group1">

    <input type="text" name="field3"

    data-parsley-min3 = ".group1"
    data-parsley-min3-message = "At least 1 must be filled"
    class="group1">



    <span id="notice"></span>
    <input type="submit" value="Submit">

</form>

Check out this fiddle https://jsfiddle.net/xcoL5Lur/6/

like image 84
Nnamdi Ukwu Avatar answered Jan 04 '23 02:01

Nnamdi Ukwu