Skip to content

Instantly share code, notes, and snippets.

@gicolek
Last active February 13, 2020 07:54
Show Gist options
  • Save gicolek/c4274380b65b5c7ba55d to your computer and use it in GitHub Desktop.
Save gicolek/c4274380b65b5c7ba55d to your computer and use it in GitHub Desktop.
Gravity Forms Recover Password Validation
<?php
// remember, the hook suffix, should contain the form id!
add_filter( "gform_field_validation_2", 'wp_doin_validation_2', 10, 4 );
/**
* Let's verify for the user email or username provided
*
* @return ARRAY_A
*/
function wp_doin_validation_2($result, $value, $form, $field) {
$classes = explode( ' ', $field['cssClass'] );
// let's assume it's all valid
$result['is_valid'] = true;
// lets check if the user with such a username is already in the database
if ( in_array( 'user-email', $classes ) ) {
// this means that the user has specified email
if ( strpos( $value, '@' ) ) {
$user_data = get_user_by( 'email', trim( $value ) );
if ( empty( $user_data ) ) {
$result['is_valid'] = false;
$result['message'] = 'No such email in database.';
}
$allow = check_if_reset_is_allowed( $user_data->ID );
} else {
// let's verify the username existence
$user_id = username_exists( $value );
if ( !$user_id ) {
// let's mark this field is invalid
$result['is_valid'] = false;
$result['message'] = 'No such user in database.';
}
$allow = check_if_reset_is_allowed( $user_id );
}
}
// if the password change is not allowed return false
if ( !$allow ) {
// let's mark this field is invalid
$result['is_valid'] = false;
$result['message'] = 'Password change is not allowed.';
}
return $result;
}
/**
* Utility to check if password reset is allowed based on user id.
*
* @param INT $user_id
* @return BOOL true / false
*/
function check_if_reset_is_allowed($user_id) {
$allow = apply_filters( 'allow_password_reset', true, $user_id );
if ( !$allow ) {
return false;
} elseif ( is_wp_error( $allow ) ) {
return false;
}
return true;
}
@moabi
Copy link

moabi commented Feb 13, 2020

In order to get the Email/Username Field, we should do :

$username_email_field_ID = 1;
	foreach ( $form['fields'] as $field ) {
		if($field->cssClass === 'user-email'){
			$username_email_field_ID = isset($field->id) ? $field->id : 0;
		}
	}
	// get the submitted value
	$email_or_username = $_POST['input_'.$username_email_field_ID];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment