Data Validation - stop form submission if added contacts doesn't equal indicated number to be added

Prev Next

This Javascript checks to see if the number of passengers to be carried (a number entered into a specific custom field) isn't matched by the number of contacts added within a repeating block.

If the number of passengers matches the number of contacts added through a repeating block match, the form can be submitted. If the numbers are different display a message to the form user indicating this situation.

This was a specific requirement from a client where users were interacting with the form on a mobile, and despite indicating that there should be a certain number of passengers, they were losing track of the passengers details entered, and were submitting the form between the number of passengers, and the passenger details for each passenger.

This could be modified to suit situations where you want to have a record of the number of contacts that should be recorded on a form, and ensure that the number of contacts added through a repeating block, actually match.

For example, number of family members that should be added to a form, and confirming that they were.

Regarding the script below:

  • number-of-passengers - this is the CSS class name that's been added to the label and field that contains the numeric value of the number of passengers.
    image.png

  • passenger - this is the CSS class name that's been added to the label and field of the name of the passenger name field added to a repeating block.
    image.png

</style>

<script>
function userPageLoaded() {
    $("#infoodle_form").attr("onsubmit", "return doCustomValidation()");
}

function doCustomValidation(){
    const passengerCount = $(".number-of-passengers").find("input").val();
    const passengerNameCount = $(".passenger").length;
    
    if (passengerCount && (passengerCount != passengerNameCount)) {
        $(".number-of-passengers").find("input").focus();
        alert('The number of passengers added does not match the number provided in the "Total number of passengers today" field.');
        return false;
    }
    
    return do_submitform();
}
</script>

<style>