You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于为Contact Form 7的text* your-name设置Pattern="[A-Za-z]"的技术问询

Solution for Contact Form 7 Name Field Only Allowing Letters

Hey, I see exactly what's going on here—your current pattern="[A-Za-z]" only matches a single letter somewhere in the input, not the entire field. That's why entries with mixed letters and numbers are still getting through. Let's fix this with two solid approaches:

1. Fix the Frontend Pattern Validation

First, update your text* tag to use a pattern that enforces the entire input is made up of letters (and optionally spaces for full names). Here's the corrected code:

<label> Your Name (Required) 
<p>[text* your-name placeholder "Name" pattern="^[A-Za-z\s]+$"] </p>
</label>

What this pattern does:

  • ^ Anchors the match to the start of the input
  • [A-Za-z\s] Allows uppercase letters, lowercase letters, and spaces (remove \s if you don't want to permit spaces in names)
  • + Ensures there's at least one valid character (works alongside the text* required flag)
  • $ Anchors the match to the end of the input, so no non-letter characters can be anywhere in the field

If you need to support names with hyphens or apostrophes (like O'Neil or Mary-Anne), adjust the pattern to:
pattern="^[A-Za-z\s'-]+$"

2. Add Backend Validation (Critical for Security)

Frontend validation can be bypassed, so adding a backend check ensures no invalid submissions get through even if someone tampers with the frontend code. Add this to your theme's functions.php file (or a custom plugin):

add_filter( 'wpcf7_validate_text*', 'custom_name_validation_filter', 10, 2 );

function custom_name_validation_filter( $result, $tag ) {
    // Target the "your-name" field specifically
    if ( 'your-name' === $tag->name ) {
        $submitted_name = isset( $_POST['your-name'] ) ? sanitize_text_field( $_POST['your-name'] ) : '';
        
        // Validate against our regex pattern
        if ( !preg_match( '/^[A-Za-z\s]+$/', $submitted_name ) ) {
            $result->invalidate( $tag, 'Please enter a valid name using only letters and spaces.' );
        }
    }
    return $result;
}

Extra Tips:

  • Customize the error message in the backend function or directly in your CF7 form settings (under the field's "Error message" option)
  • Test edge cases: try entering John123, !@#Mary, and Jane Doe to make sure validation works as expected
  • If you only want single-word names, remove the \s from both the frontend pattern and backend regex

内容的提问来源于stack exchange,提问作者Saxena Ameet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:14:33