0

I have registered a setting with a callback function:

register_setting( 'my-plugin-settings-group', 'notification_email', 'email_validation' )

and callback function looks like:

function email_validation($data) {

    if (null == $data)
    {
        add_settings_error(
            'requiredTextFieldEmpty',
            'empty',
            'Notification Email cannot be empty',
            'error'
        );
    }
    else {

        if (!is_email($data)){
            add_settings_error(
                'requiredTextFieldEmpty',
                'empty',
                'Notification Email is not valid email address',
                'error'
            );
        }

        else { return $data; }
    }
}

Validation works fine but when it fails (empty field or not valid email address) it erases data from that field.

Is there any way to prevent that?

1 Answer 1

1

in case of wrong value, the function has to return the original value then try this :

function email_validation($data, $option, $original_value) {

    if (null == $data)
    {
        add_settings_error(
            'requiredTextFieldEmpty',
            'empty',
            'Notification Email cannot be empty',
            'error'
        );

        return $original_value;
    }
    else {

        if (!is_email($data)){
            add_settings_error(
                'requiredTextFieldEmpty',
                'empty',
                'Notification Email is not valid email address',
                'error'
            );

            return $original_value;
        }

        else { return $data; }
    }
}
2
  • The idea is right but it came that $original_value is empty when that function was called. Jun 29, 2016 at 16:03
  • I have added $original_value = esc_attr( get_option('notification_email') ); as a first line of the function to get it work. Jun 29, 2016 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.