web-dev-qa-db-ja.com

コメントフォームの検証

コメントフィールドに入力規則を設定するにはどうすればよいですか。

私はコメント名/メールアドレス/ホームページのonmouseoverとonblurの値を変更します(ラベルの代わりにこれを使います - フィールドが空の場合は "Your e-mail"、 "Your homepage"などと表示されます)。問題は、送信時にホームページのフィールドにこのテキストを送信することです([email protected]以外のものを入力した場合にエラーが発生するEメー​​ルフィールドとは異なり、検証は行われません)。

ホームページフィールドを検証する方法

3
Kilgore_Trout

コメント処理はファイルwp-comments-post.phpで行われます。コメントフォームフィールドに入力された値を検証するためにフックpre_comment_on_postを使用することができます。

function custom_validate_comment_url() {
    if( !empty( $_POST['url'] ) && !preg_match( '\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]', $_POST['url'] ) // do you url validation here (I am not a regex expert)
        wp_die( __('Error: please enter a valid url or leave the homepage field empty') );
}

add_action('pre_comment_on_post', 'custom_validate_comment_url');

送信した値を変更したい場合は、フィルタpreprocess_commentを使用してください。例えば。:

function custom_change_comment_url( $commentdata ) {
    if( $commentdata['comment_author_url'] == 'Your homepage' )
        $commentdata['comment_author_url'] = '';
    return $commentdata;
}

add_filter('preprocess_comment', 'custom_change_comment_url');
7
sorich87