skip to Main Content

I have a form validation that, so far, returns an error message if either of two defined words/phrase are present in the input area:

add_filter('gform_validation_3', 'custom_validation');
function custom_validation($validation_result){
    $form = $validation_result["form"];
    foreach($form['fields'] as &$field){
        /* Check that the value of the field that was submitted. e.g. the name="input_1" that is generated by Gravity Forms */
        if($_POST['input_4'] == "Your First Name" || "SEO"){
         // 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"] = "This field needs to be your actual first name.";
             }
         }
        }
    //Assign modified $form object back to the validation result
    $validation_result["form"] = $form;
    return $validation_result;
}

I’m not sure now how to create an array to define the words that are not allowed, so that I can have a much longer list?

2

Answers


  1. You can use function in_array()

    <?php
    
    $blacklisted = ['some', 'ugly', 'bad', 'words'];
    
    if(in_array('ugly', $blacklisted)){
      echo('bad word spotted');
    }
    

    demo: https://repl.it/@kallefrombosnia/DarkvioletDeepPolygons

    Login or Signup to reply.
  2. First of all, the first “if” is incorrect, I think you meant:

    if($_POST['input_4'] == "Your First Name" || $_POST['input_4'] =="SEO")
    

    A good way to achieve what you long is:

    $forbidden_words = ["Your First Name", "SEO"];
    $is_valid = !in_array($_POST['input_4'], $forbidden_words); //false if the word is in array
    

    After that you may go:

    if($is_valid)
         //do magic
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search