Create a rule if the sum of 2 fields exceeds a given number the user get an "error" messag

I'd like to create a rule if the sum of 2 fields exceeds a given number the user get an "error" message.

  • Ash
    • WordPress Hacker

    Hello Arom77

    This is not possible out of the box I am afraid. But, I have sent your query to our second level support team. I can't confirm if they can provide a solution easily or not but they will take a look at the options. Please note that, they deal with more complex issues, so there might be little delay. We appreciate your patience on this.

    Have a nice day!

    Cheers,
    Ash

  • Konstantinos Xenos
    • Rubber Duck Debugger

    Hi Arom77 ,

    I've made a mu-plugin for you as an addition that verifies the fields sum to your liking. You can easily set it up by following these instructions:

    Always make sure to keep a backup of your site before changing/adding custom code.

    1] Navigate to your /wp-content/ directory and create a new one named mu-plugins if it doesn't exist.
    2] Inside the mu-plugins folder create a file named forminator-custom-sum.php
    3] Edit the file and copy / paste this code snippet inside.

    <?php
    
    add_filter(
    	'forminator_custom_form_submit_errors',
    	function( $submit_errors, $form_id, $field_data_array ) {
    		// Change number '5' to your Form ID ( you can find that from the shortcode provided ).
    		if ( 5 == $form_id ) {
    			// Change number '20' to the max value that you want to set.
    			$max_value = 20;
    
    			// Change 'number-1' and 'number-2' to the field names that you have in the form.
    			$number_one = isset( $_POST['number-1'] ) ? intval( $_POST['number-1'] ) : 0;
    			$number_two = isset( $_POST['number-2'] ) ? intval( $_POST['number-2'] ) : 0;
    
    			$total_value = intval( $number_one + $number_two );
    
    			if ( $total_value > $max_value ) {
    				// Change  'The total value is not correct' to the error message that you like to show.
    				$submit_errors[]['submit'] = 'The total value is not correct';
    			}
    
    			return $submit_errors;
    		}
    	},
    	15,
    	3
    );

    4] Save and close the file.
    5] The final path should look like /wp-content/mu-plugins/forminator-custom-sum.php

    You should make some adjustments to the code above but I have added comments so you can easily follow along and alter it as needed. As an example I'm using 2 number fields ( number-1, number-2 ) and if they are bigger than 20 ( $max_value ) then the form returns an error. In the screenshots I've marked with a red outline the fields and form ID that are needed for the code to work so you can easily change it as well as the resulting error.


    Tell me if you need further help with this!

    Regards,
    Konstantinos

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.