DEV Community

Renzo Zamora
Renzo Zamora

Posted on

Validate form fields in Elementor

Elementor Pro is always a good option if you want to have an almost complete suite to design a website and have basic functionalities for basic needs of the process.

One of the most important widgets is the forms widget or also called Elementor Forms.

Elementor Forms allows us to generate forms quite fast and functional for different needs, also the "Actions after submit" (actions after pressing the submit button) are quite useful and best of all that can be combined, ie you can add a person to a mailing list, send a message to the administrator and another to the one who sent the form, send a webhook to Zapier or other similar service and at the end redirect the user to a thank you page.

However, there is a problem if you want to make a form for serious use. There are no really useful validations in them.

How? Elementor only has basic frontend validation using matches and required on the fields. Someone using the Element Inspector of any browser can modify the code and submit any information without being validated accordingly.

Some people also opt for pure Javascript or jQuery libraries to validate the forms, but that gives another problem which is to add an additional weight to the one that already has Elementor and its libraries. And disabling Javascript all those validations go down the drain.

Is there a solution?

Yes, the validations by backend. By doing it this way, the end user, even if he uses the inspector or disables javascript, the data will still be validated.

Elementor Forms has hooks that allow backend validation and return error messages in real time via Ajax.

How to implement it?

You must create a plugin or edit the functions.php file of your theme (I recommend working with a child theme) to add these validations.

Ok, but what is the code?

You have it below:

Email validation

The validation that comes by default in Elementor basically looks for an at (@) and a dot (.), which does not help much to have valid emails.

Placing the following code you will have a much more accurate validation:

add_action( 'elementor_pro/forms/validation/email', function( $field, $record, $ajax_handler ) {
    if ( !filter_var(  $field['value'], FILTER_VALIDATE_EMAIL ) ) {
        $ajax_handler->add_error( $field['id'], 'Please enter a valid email.' );
    }
}, 10, 3 );
Enter fullscreen mode Exit fullscreen mode

Validation by field ID

Each field in Elementor Forms has an ID that we can customize. Thanks to this, we can make a general validation in all the forms of our site where the fields have the same ID.

First, we will add this function that allows us to get a field by the ID entered.

// This function allows to obtain a field by ID, if it does not exist it returns FALSE.
function rnz_elementor_get_field( $id, $record )
{
    $fields = $record->get_field( [
        'id' => $id,
    ] );

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

    return current( $fields );
}
Enter fullscreen mode Exit fullscreen mode

As a second step, we create the function where we will validate the fields. This is referential, you can modify it to your needs.

function rnz_elementor_forms_validation( $record, $ajax_handler ) {

    // Validate that the privacy policy field is checked.
    // This is useful for when you want to add custom notifications.
    if( $field = rnz_elementor_get_field( 'accept_terms', $record ) )
    {
        if( $field['value'] != 'on' ){
            $ajax_handler->add_error( $field['id'], 'You must accept the policies to submit the form.' );
        }
    }

    // Remove spaces before and after the text, if any, and verify that it is not an empty entry.
    if( $field = rnz_elementor_get_field( 'name', $record ) )
    {
        if( $field['required'] == 'yes' ){
            if( empty( trim($field['value']) ) ){ // Check if it is empty
                $ajax_handler->add_error( $field['id'], 'Please enter your name.' );
            } else if( 3 >= strlen(trim($field['value'])) ){
                $ajax_handler->add_error( $field['id'], 'Your name must have at least 3 digits.' );
            }
        }
    }

    if( $field = rnz_elementor_get_field( 'age', $record ) )
    {
        if( $field['required'] == 'yes' ){
            if( empty( trim($field['value']) ) ){
                $ajax_handler->add_error( $field['id'], 'Please enter your age.' );
            } else if( filter_validate( trim($field['value']), FILTER_VALIDATE_INT )  ){
                $ajax_handler->add_error( $field['id'], 'Only numbers for your age are accepted.' );
            }
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Finally, we must add the action to make it all work.

add_action( 'elementor_pro/forms/validation', 'rnz_elementor_forms_validation', 10, 2 );
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
scratchcodeio profile image
Scratch Code

Your code help me to develop new functionality in Elementor. I have changed the way of showing elementor form error from beneath input to above the form input. It will show all the error messages above the form.

Collapse
 
serery profile image
viqih

can you please help me how i can change order of error message to above the input field

Collapse
 
waresulahammad profile image
Waresul Ahammad

This code is well. But I face a problem.

I have two email fields one is "Enter_Email" and "Confirm_Email"

if this "enter_email" === "confirm_email" same then the Elementor pro will be submit, otherwise it will not be submitted. How can I do it?

Please reply me with your talent. Thank you very much.

Collapse
 
cdsaenz profile image
Charly S.

Excellent! Very useful. But is there a way to show multiple errors for a field? I have a field with two validations and only the last one shows in the frontend.

Collapse
 
cdsaenz profile image
Charly S. • Edited

Self answer, pass an array of errors!

$fields      = $record->get( 'fields' );
$field_value = $fields['nameField']['value'];
$errors      = [];

if ( strpos( $field_value, '.' ) !== false ) {        
        $errors[] = 'Field must not contain a dot (.)';
}   

if ( strlen( $field_value ) > 10 ) {
        $errors[] = 'Field must be no longer than 10 characters';
}

$ajax_handler->add_error( 'nameField', $errors );
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ira1203 profile image
ira1203

is it possible to get rid of fields tool error message from browser or change it to my own text?

Collapse
 
mkyy profile image
mkyy

yeah it is, just go to Additional Options and set Form Validaiton to Custom, then right on the next option you can set your own messages.