Elementor Dependent Fields Validation - DBarakMedia - Business Process Automation Services
dbarak-media-business-process-automation-services-practical-code

Elementor Dependent Fields Validation

If you use Elementor page builder in WordPress you know that sometimes you need to validate a field in an Elementor form. For example, you have a phone form field and you need to validate the phone number that users will type into this field EXACTLY according to the way phone numbers are used in your country or state. If the user’s entry will not be validated there is a need to display an error message right below the phone field and stop the form’s submission. In order to do this kind of validation there is no other way but to use Elementor’s Forms API and paste some PHP code as a snippet.

Click here to read more about Elementor’s Forms API.

To continue the example from what I have written above, I have copied the following code from Elementor’s Forms API page and changed it as follows: 

				
					// Validate the phone_eng field is in regex format.
add_action( 'elementor_pro/forms/validation', function ( $record, $ajax_handler ) {
    $fields = $record->get_field( [
        'id' => 'phone_eng',
    ] );

    if ( empty( $fields ) ) {
        return;
    }

    $field = current( $fields );

    if ( 1 !== preg_match( '/\+[0-9]{8,}/', $field['value'] ) ) {
        $ajax_handler->add_error( $field['id'], 'Only numbers and international prefix with one + at the start are allowed' );
    }
}, 10, 2 );
				
			

As you see in the code above, in line 4 I have changed the PHP code to select the phone field according to its id i.e. you have to name the phone filed in your Elementor’s form EXACTLY as you write it here , in my case it the id is ‘phone_eng’. Look at the following photo to see where to set the id of an Elementor’s form field. You’ll have to select the filed in the Elemntpr’s form editor then click on the ‘ADVANCED’ tab and then set the ‘ID’ of the field.

dbarak-media-business-process-automation-services-elementor-form-id-example

In line 11 I get the actual phone field from the ‘$fields’ array by using the ‘current’ function, and the in line 13 I test the value of the field with a regular expression (this is a regex for an Israeli phone number, so you’ll have to adjust the regex according to the format used in your state of country. Then in line 14 an error message will be displayed right below the phone files, you see that the ‘add_error’ function of the ‘$ajax_handler’ take as its first parameter, the id of the field i.e. $field[‘id’]. The submission of the form will also stop after the error message will be displayed to the user.

The PHP code will be pasted in to a snippet by using the FREE WordPress plugin called: ‘Code Snippets’. Click ‘Plugins’ in the Wrodpress menu then on the ‘Add New’ button, then search for this plugin, install and activate it. Then paste the code above into a new snippet and you’ll see that the phone field’s validation is working as I’ve described. See the photo below to make sure that you have found the right plugin (Note that you can also paste the code into you child theme’s functions.php file, I gave you the easy option here :-).

Dependent Fields Validation

Now imagine an Elementor form for collecting friend’s recommendations i.e. it has TWO steps ( it is an Elementor’s Multi-Step form). In the first step the user that wants to recommend something (e.g. a product or a service) to his friends, will enter his name and phone number, then he will click the ‘Next’ button and see the second step in which there will be 5 pairs of fields, as follows:

Friend’s Name ____     |    Friend’s Phone ____

Friend’s Name ____     |    Friend’s Phone ____

Friend’s Name ____     |    Friend’s Phone ____

Friend’s Name ____     |    Friend’s Phone ____

Friend’s Name ____     |    Friend’s Phone ____

The validation that is required now is more complicated than a simple one field validation. The name and phone field of the recommending user are simply set as “Required” in Elementor’s form editor and the phone field’s validation will take place as I have described above. BUT, what about the validations for the 5 pairs of Name and Phone fields I’ve written above ???

Well, it is up to you as the designer of the form, but the logical thing to do in this case is to do it as follows:
The first friend’s fields i.e. the first pair of Name and Phone fields will also be defined as “Required”, but the rest of the Name | Phone pairs can’t be mandatory because we want the recommending user to enter at LEAST one friend but not more than that, only if he wants to add more friends he can do so. Hence the validation will be as follows: ONLY if the user will enter a friend’s name, in one of the other 4 Name | Phone pairs of fields, and then try to submit the form, the corresponding Phone field will be mandatory and an error message will be displayed below this Phone field asking the user to also enter the Phone, and the submission will stop, and vice versa, if the user will enter a Phone without entering the corresponding Name, he will see an error message below the Name field asking him to also enter the Name of the friend.

You see that this is a validation of fields that depend on each other, this is a different kind of validation.           

Changing the validation code

I have changed the validation code and created a NEW snippet for each of the other Name | Phone pairs of fields. Each snippet will trigger the error for ONE pair of Name | Phone fields. So a total of 4 snippets were created to take care of all of the required validation. The id of each of the fields in each pair were set as follows: (‘name1’, ‘phone1’), (‘name2’, ‘phone2’), etc.. until the fifth pair.

I have changed the code as you see below. E.G. for the second pair of fields, I used the same method as I’ve described above but this time using the id of the Phone field in line 5 AND the id of the Name field in line 17. Then, getting each field itself in the variables $phone2 and $name2 in lines 12 and 24.

Finally, in lines 27 until 29, I handled the case where the user entered the Name field but did NOT enter the corresponding Phone field. The error message will be displayed below ‘phone2’ field. You can also see that it is possible to use the id of the field as a string in the add_error function, in line 28. In lines 32 until 34 I handled the opposite scenario in which the user entered the phone but did NOT enter the corresponding Name field.

I addition to all of the above I also added a validation to each phone field as I explained above, I used 6 snippets this time , for each phone field, because ALL of the phone fields need to be validated (i.e. 1 user phone field + 5 friend’s phone fields).

As a side note I added in lines 37 until 43 a code that will help you debug this code snippet, since there is no direct output or alert client side code you can use for that. The code is sending an email (replace {{use your email here}} with your email) with the values of the phone and name fields so you’ll know your code works.

Now, enjoy validating your Elementor forms 🙂 

				
					add_action( 'elementor_pro/forms/validation', function ( $record, $ajax_handler ) {
    
	////phone2
    $fields = $record->get_field( [
        'id' => 'phone2',
    ] );

    if ( empty( $fields ) ) {
        return;
    }

    $phone2 = current( $fields );


	////name2
    $fields = $record->get_field( [
        'id' => 'name2',
    ] );

    if ( empty( $fields ) ) {
        return;
    }

    $name2 = current( $fields );
    
	
    if ( $phone2['value'] === '' && $name2['value'] !== '' ) {
        $ajax_handler->add_error( 'phone2', 'Please enter the Phone number' );
    }


    if ( $phone2['value'] !== '' && $name2['value'] === '' ) {
        $ajax_handler->add_error( 'name2', 'Please enter a Name' );
    }


    //$output = 'phone2 value is: ' .  $phone2['value'] . ' | name2 value is: ' . $name2['value'];

    //$headers = "Content-Type: text/html; charset=UTF-8\r\n";

    //$txt .= '<pre style="direction:ltr;">'. print_r ($output, true) . '</pre>';

    //$send = wp_mail('{{use your email here}}', 'Output',  $txt, $headers);


}, 10, 2 );
				
			
Scroll to Top