简体   繁体   中英

Gravity forms validation on number field

The Gravity form phone number field is supposed to validate a telephone number, but if the field option is set to "international" then the form submits if the data in the field are standard characters.

The code below hooks into my form and specific field, but I am having problems with how to check if the field string is a number.

// add custom validation to the gravity forms plugin to validate "phone number" field
add_filter("gform_field_validation_2_4", "custom_validation", 10, 4);

function custom_validation($result, $value, $form, $field){

if($result["is_valid"] && intval($value)){

$result["is_valid"] = false;

$result["message"] = "Please enter a valid telephone number";

}
return $result;
}

I would appreciate your advice and feedback.

Thanks, JB.

Why don't you try with a regular expression? It works great for such cases. For example (untested):

// add custom validation to the gravity forms plugin to validate "phone number" field
add_filter("gform_field_validation_2_4", "custom_validation", 10, 4);

function custom_validation($result, $value, $form, $field){

    if(!preg_match('~^\d+$~', $value)){
        $result["is_valid"] = false;
        $result["message"] = "Please enter a valid telephone number";
    }

    return $result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM