最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugin development - How do I add a 5 digit ZIP code validation to a Contact7 form?

programmeradmin0浏览0评论

I have an address form generated via Contact7. I need to validate there is a 5 digit zip code.

According to the docs, I came up with this function and placed it in my functions.php file

add_filter( 'wpcf7_validate_text*', 'custom_zip_validation_filter', 20, 2 );


function custom_zip_validation_filter( $result, $tag ) {
  if ( 'zip' == $tag->name ) {
    $zip = isset( $_POST['zip'] ) ? trim( $_POST['zip'] ) : '';
    $result = '/^([0-9]{5})?$/i';
  
    if (!preg_match($result, $zip, $matches)) {
            $result->invalidate($tag, "Please enter a valid zip code" );
        }
  }
  
  return $result;
}

Then in my Contact7 form, I put this line for the zip code [text* zip class:zip id:zip placeholder "ZIP"]

However, when I go to the form and input the ZIP code, I am able to submit a ZIP code of less than 5 digits or greater than 5 digits.

How can I get the error message "Please enter a valid zip code?" to appear when a user inputs a ZIP code != 5 digits?

发布评论

评论列表(0)

  1. 暂无评论