联系表 7 验证最小长度

Contact Form 7 Validate Minlength

首先,我使用的是最新的 WordPress 和 CF7 版本。我想在之前包括 tel 字段的最小长度验证。我知道语法 minlength="" 可以在CF7里面用,不知道什么原因,用不了。只有maxlength=""可以。

我已经联系了插件支持,但似乎没有进一步的回应。因此,我在这里搜索并找到了一些代码并对其进行了编辑,以便如果用户输入的字符少于 10 个,该字段将 return 出错。我把代码放在 functions.php

function custom_phone_validation($result,$tag){
   $type = $tag['type'];
   $name = $tag['name'];
   if($name == 'Subject'){
       $phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
       if($phoneNumber < "9"){
           $result->invalidate( $tag, "phone number is less" );
       }
   }
   return $result;
   }
   add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
   add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);

现在的结果是,它总是显示 "phone number is less",即使我插入了 9 个以上的字符。 请问哪里出了问题,如何解决?

你的$phoneNumber是一个字符串。您将需要获取字符串的长度以与 9 进行比较。

您的代码将变为:

function custom_phone_validation($result,$tag){
    $type = $tag['type'];
    $name = $tag['name'];
    if($name == 'Subject'){
        $phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
        if(strlen($phoneNumber) < 9){//<=====check here
            $result->invalidate( $tag, "phone number is less" );
        }
    }
    return $result;
}
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);

根据我的测试,您必须有 tel 字段 [tel* phonenumber tel-503],其中 phonenumber 是您要发布的后域的名称,代码中的第二个问题是 $name=='Subject'因为您正在验证 tel,所以 $name 将是 phonenumber。所以它会是这样的:

function custom_phone_validation($result,$tag){
   $type = $tag['type'];
   $name = $tag['name'];
   if($name == 'phonenumber'){
   $phoneNumber = isset( $_POST['phonenumber'] ) ? trim( $_POST['phonenumber'] ) : '';
   if(strlen($phoneNumber) < 9){
       $result->invalidate( $tag, "phone number is less" );
   }
  }
  return $result;
  }
add_filter('wpcf7_validate_tel','custom_phone_validation', 10, 2);
add_filter('wpcf7_validate_tel*', 'custom_phone_validation', 10, 2);