2
0

More than 3 years have passed since last update.

Contact Form 7とJavaScriptで特殊なバリデーションをする方法

Posted at

やりたいこと

contact-form-7で、特殊なバリデーションをして欲しいと言われました。

例えば、言われたこととしては ↓

  • 半角英数字、大文字でかつ10文字の規制をお願いします。
  • これは極端な話、aと入力したら自動でAとなる。と思っていいですよね。

これを実現したい場合、下記のように実装すると出来るようになります。

contents-form7

フォームでは、idを用いて操作します。

[text* coupon-code-2-1 class:secure-key id:Name01]

functions.phpに追加

固定ページで、jQueryを使うために、カスタムJSを使えるようにします。functions.phpの最後にこれを追加してください。


//Custom JS Widget
add_action('admin_menu', 'custom_js_hooks');
add_action('save_post', 'save_custom_js');
add_action('wp_head','insert_custom_js');
function custom_js_hooks() {
    add_meta_box('custom_js', 'Custom JS', 'custom_js_input', 'post', 'normal', 'high');
    add_meta_box('custom_js', 'Custom JS', 'custom_js_input', 'page', 'normal', 'high');
}
function custom_js_input() {
    global $post;
    echo '<input type="hidden" name="custom_js_noncename" id="custom_js_noncename" value="'.wp_create_nonce('custom-js').'" />';
    echo '<textarea name="custom_js" id="custom_js" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_js',true).'</textarea>';
}
function save_custom_js($post_id) {
    if (!wp_verify_nonce($_POST['custom_js_noncename'], 'custom-js')) return $post_id;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
    $custom_js = $_POST['custom_js'];
    update_post_meta($post_id, '_custom_js', $custom_js);
}
function insert_custom_js() {
    if (is_page() || is_single()) {
        if (have_posts()) : while (have_posts()) : the_post();
            echo '<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><script type="text/javascript">'.get_post_meta(get_the_ID(), '_custom_js', true).'</script>';
        endwhile; endif;
        rewind_posts();
    }
}

カスタムjs

で、最後に、カスタムjsに下記をコピペしてください。

/**
 * 半角英数字かチェック
 * @return true:半角英数字である(もしくは対象文字列がない), false:半角英数字でない
 */
function isHalfWidthAlphanumeric(value) {
  if ( value == null )
    return;
  if( value.match( /[^A-Za-z0-9\s.-]+/ ) ) {
    alert("半角英文字で入力してください");
    return false;
   }
   return true;
}

$(function(){$("#Name01").blur(function(){ if ( !isHalfWidthAlphanumeric($(this).val()) ) { $(this).focus(); } });});
$(function(){$("#Name01").blur(function(){document.getElementById("Name01").value=$(this).val().toUpperCase();});});
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0