Skip to content

Instantly share code, notes, and snippets.

@verticalgrain
Created May 28, 2015 18:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save verticalgrain/ec2146504981e2561a83 to your computer and use it in GitHub Desktop.
Save verticalgrain/ec2146504981e2561a83 to your computer and use it in GitHub Desktop.
Email validation in Gravity Forms - validate an email address entered in a regular text input
<?
/**
* Hooks for validating an email address in Gravity Forms
* When using a plain text input to collect an email, this will validate that the email address entered is a proper email address
* Useful for situations in which the existing gravity forms email field can't be used
*
* Change line 28 and line 37 to adapt this to your form
*
* @package d7
* @subpackage boilerplate-theme
*
* @param array $validation_result Contains the form data Gravity Forms passes at this point
*
*/
// Validate the email field
// Since we are using the gravity forms post fields, we can't use the default gravity forms email validation
add_filter('gform_validation', 'custom_validation');
function custom_validation($validation_result){
// Set the $validation_result object to $form for clarity
$form = $validation_result["form"];
// Get the value the user entered for the email field
// EDIT HERE WITH THE INPUT NAME OF YOUR FIELD (input_2 is the name attribute of the input field)
$email = $_POST["input_2"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// set the form validation to false
$validation_result["is_valid"] = false;
// specify the invalid field and provide custom validation message
// EDIT HERE WITH THE ZERO INDEXED NUMBER OF THE FIELD (in thise case $form["fields"][2], because the field is the third field in the form)
$form["fields"][2]["failed_validation"] = true;
$form["fields"][2]["validation_message"] = 'Please enter a valid email address';
}
// update the form in the validation result with the form object you modified
$validation_result["form"] = $form;
return $validation_result;
}
@FLSouthPaw
Copy link

Thank You!

@arnaud-izzi
Copy link


    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    	// set the form validation to false
    	$validation_result["is_valid"] = false;

		foreach ($form['fields'] as &$field) {
			if ($field->id == 2) { //input id
				$field->failed_validation = true;
				$field->validation_message = 'Please enter a valid email address';
			}
		}

    }

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