Skip to main content

[Thủ Thuật WP] Kiểm tra số điện thoại và textarea trong Contact Form 7

Code snippet WordPress cho tính năng "Kiểm tra số điện thoại và textarea trong Contact Form 7".

Plugin Contact Form 7 là plugin phổ biến của WordPress. Bạn để ý thường những contact spam thường số điện thoại không hợp lệ ở Việt Nam hoặc Textarea ô lời nhắn, nội dung chứa link (URL). 

Dưới đây là hướng dẫn giúp bạn thực hiện điều đó. Mờ file functions.php và chèn đoạn code bên dưới:

// kiem tra so dien thoai cua VN (doi so moi nhat)
function custom_filter_wpcf7_is_tel($result, $tel)
{
  $result = preg_match('/^(0|\+84)(\s|\.)?((3[2-9])|(5[689])|(7[06-9])|(8[1-689])|(9[0-46-9]))(\d)(\s|\.)?(\d{3})(\s|\.)?(\d{3})$/', $tel);
  return $result;
}

add_filter('wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2);

// Kiem tra textarea
function custom_textarea_validation_filter($result, $tag)
{
  $type = $tag['type'];
  $name = $tag['name'];
  $value = $_POST[$name];
  $Match_all = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]|[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,8}/";
  if (preg_match($Match_all, $value)) {
    $result->invalidate($tag, "Nội dung gửi không hợp lệ!");
  }
  return $result;
}

add_filter('wpcf7_validate_textarea', 'custom_textarea_validation_filter', 10, 2);
add_filter('wpcf7_validate_textarea*', 'custom_textarea_validation_filter', 10, 2);