Search code examples
contact-formcontact-form-7

How to add required attribute on contact form 7?


I want to add required attribute additionally on contact form.

Screenshots

<textarea name="your-message" required="required" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="your-message" aria-required="true" aria-invalid="false"></textarea>

How can I do in backend form?

[textarea* your-message id:your-message] <label for="your-message">Message</label>

Please help me.

Thanks


Solution

  • If you're trying to add the html5 required attribute to a form tag in Contact Form 7. You can filter the form content and include it. However, since the form submission is ajax, it won't really do anything unless you disable that also.

    You can use the hook wpcf7_form_elements to filter the output and do a find/replace.

    By looking for name="your-field-name" you specify the input / textarea tag vs the span that wraps the form tags.

    <?php
    // Filter Form Elements
    // Include in your child theme/theme's functions.php
    add_filter( 'wpcf7_form_elements', 'dd_wpcf7_form_elements_replace' );
    function dd_wpcf7_form_elements_replace( $content ) {
        // $name == Form Tag Name [textarea* your-message] 
        $name = 'name="your-message"';
        $str_pos = strpos( $content, $name );
        if (false !== $str_pos) {
            $content = substr_replace( $content, ' required="required" ', $str_pos, 0 );
        }
        return $content;
    }
    

    This above will output.

    <textarea required="required" name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false"></textarea>