user2185592
user2185592

Reputation: 388

Parsley Validator - At least one field is required

I have four input elements (i.e. textboxes) in my form for user to enter different phone nos i.e. office, handphone, home, etc. (These input fields are not necessarily under one div/group) Before submit, I want to validate these phone no. entries and make sure that atleast one of the phone no is entered by user. If none of the phone no. field has valid entry my form should not get validated and should not post.

I use ParsleyJS library for validation and use knockout.js.

I have following code for one field in my Razor view (rest three fields are similar to this):

        <div class="col-md-3 clmargin">
            <div class="form-group col-md-4 zeropadding div2adjustments">
                @Html.LabelFor(m => m.Handphone, new { @class = "fieldtext" })
            </div>
            <div class="col-md-8 ">
                <input type="text" class="form-control fieldtextinput input-sm" maxlength="10" minlength="8" data-parsley-type="digits"
                       data-bind="value:Handphone, disable:ViewMode() == 'View'" id="handphone">
            </div>
        </div>

I have given id to my input i.e. "handphone" in above code.

Javascript code :

$(document).ready(function () {
    $('#contact').parsley().subscribe('parsley:form:validate', function (formInstance) {

        // if one of these blocks is not failing do not prevent submission
        // we use here group validation with option force (validate even non required fields)
        if (document.getElementById("other").value == '' && document.getElementById("telephone").value == '' &&
            document.getElementById("office").value == '' && document.getElementById("handphone").value == ''){
            // else stop form submission
            formInstance.submitEvent.preventDefault();
            // and display a gentle message
            $('.invalid-form-error-message')
                .html("Provide atleast one contact no")
                .addClass("filled");
            return;
        }
        $('.invalid-form-error-message').html('');
        return;
    });
});

With above script code it can detect the invalid scenario but doesn't prevent the form submit.

I have taken above script code from here

Upvotes: 3

Views: 8731

Answers (1)

Lu&#237;s Cruz
Lu&#237;s Cruz

Reputation: 14980

There is no simple way for conditional validation in Parsley.js yet. You can take a look at Marc's answer for additional information.

You'll probably need to tweak this code to suit your needs, but you could do something like this (jsfiddle):

<div class="invalid-form-error-message"></div>
<form id="demo-form">
    <input type="text" name="field1" required data-parsley-errors-messages-disabled />
    <input type="text" name="field2" required data-parsley-errors-messages-disabled />
    <input type="text" name="field3" required data-parsley-errors-messages-disabled />
    <input type="text" name="field4" required data-parsley-errors-messages-disabled />
    <input type="submit" />
</form>

<script>
$(document).ready(function() {
    $('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
        // If any of these fields are valid
        if ($("input[name=field1]").parsley().isValid() || 
            $("input[name=field2]").parsley().isValid() || 
            $("input[name=field3]").parsley().isValid() || 
            $("input[name=field4]").parsley().isValid()) 
        {
            // Remove the error message
            $('.invalid-form-error-message').html('');

            // Remove the required validation from all of them, so the form gets submitted
            // We already validated each field, so one is filled.
            // Also, destroy parsley's object
            $("input[name=field1]").removeAttr('required').parsley().destroy();
            $("input[name=field2]").removeAttr('required').parsley().destroy();
            $("input[name=field3]").removeAttr('required').parsley().destroy();
            $("input[name=field4]").removeAttr('required').parsley().destroy();

            return;
        }

        // If none is valid, add the validation to them all
        $("input[name=field1]").attr('required', 'required').parsley();
        $("input[name=field2]").attr('required', 'required').parsley();
        $("input[name=field3]").attr('required', 'required').parsley();
        $("input[name=field4]").attr('required', 'required').parsley();

        // stop form submission
        formInstance.submitEvent.preventDefault();

        // and display a gentle message
        $('.invalid-form-error-message')
            .html("You must correctly fill the fields of at least one of these two blocks!")
            .addClass("filled");
        return;
    });
});
</script>

Note that you need to add data-parsley-errors-messages-disabled to your inputs, so you don't see the error message of each.

Upvotes: 4

Related Questions