Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ahaywood/e0888b765b951dcf891e to your computer and use it in GitHub Desktop.
Save ahaywood/e0888b765b951dcf891e to your computer and use it in GitHub Desktop.
<?php
//This is a filter to change the default validation message that Gravity Forms generates
add_filter('gform_validation_message', 'change_validation_message', 10, 2);
function change_validation_message($message, $form)
{
return "<div class='validation_error'><strong>Oops!</strong> Looks like there’s something wrong. Please review the form above.</div>";
}
// Often forms in Gravity Forms to need to start with default values and we need to check the form in case the user hasn't entered new data and give them a validation message back
// Append the Gravity Forms ID to the end of the filter so that the validation only runs on this form. In this example I'm doing it on Form #2
add_filter('gform_validation_2', 'custom_validation');
function custom_validation($validation_result)
{
$form = $validation_result["form"];
//We need to loop through all the form fields to check if the value matches and of the default values
foreach ($form['fields'] as &$field) {
//Check if the value is equal to the Default Value you entered in Gravity Forms
if ($field["value"] === "Your name") {
// set the form validation to false
$validation_result["is_valid"] = false;
//The field ID can be found by hovering over the field in the backend of WordPress
if ($field["id"] == "2") {
$field["failed_validation"] = true;
$field["validation_message"] = "Please enter your name.";
}
}
if ($field["value"] === "Job Title") {
// set the form validation to false
$validation_result["is_valid"] = false;
//The field ID can be found by hovering over the field in the backend of WordPress
if ($field["id"] == "4") {
$field["failed_validation"] = true;
$field["validation_message"] = "Please enter your job title.";
}
}
if ($field["value"] === "Contact phone number") {
// set the form validation to false
$validation_result["is_valid"] = false;
//The field ID can be found by hovering over the field in the backend of WordPress
if ($field["id"] == "5") {
$field["failed_validation"] = true;
$field["validation_message"] = "Please enter your contact phone number.";
}
}
if ($field["value"] === "Company") {
// set the form validation to false
$validation_result["is_valid"] = false;
//The field ID can be found by hovering over the field in the backend of WordPress
if ($field["id"] == "6") {
$field["failed_validation"] = true;
$field["validation_message"] = "Please enter your company name.";
}
}
}
//Assign modified $form object back to the validation result
$validation_result["form"] = $form;
return $validation_result;
}?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment