javascript 郵便番号のチェックを行う
- 2020.09.29
- javascript
- javascript

javascriptで、正規表現を用いて郵便番号(xxx-xxxx形式 数字も半角のみ)のチェックを行うサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ firefox 80.0.1
郵便番号(xxx-xxxx形式)のチェック
正規表現を使用して、チェックを行うことが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 |
var str = "111-7777"; // 郵便番号チェック 数字も半角のみ if (str.match(/^\d{3}-\d{4}$/)) { //郵便番号 console.log("郵便番号です"); } else { //郵便番号以外 console.log("郵便番号ではありません"); } // 結果 郵便番号です |
全角の場合は、郵便番号でないと判定します。
1 2 3 4 5 6 7 8 9 10 11 12 |
var str = "111-1111"; // 郵便番号チェック if (str.match(/^\d{3}-\d{4}$/)) { //郵便番号 console.log("郵便番号です"); } else { //郵便番号以外 console.log("郵便番号ではありません"); } // 結果 郵便番号ではありません |
サンプルコード
以下は、
「 判定 」ボタンをクリックすると、フォームに入力したテキストデータが郵便番号であるかを判定する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 25px; width: 500px; } </style> <script> function hoge() { // フォームの値を取得 var str = document.getElementById('str').value; // 表示用の要素 var obj = document.getElementsByClassName('badge'); // 郵便番号チェック if (str.match(/^\d{3}-\d{4}$/)) { //郵便番号 obj[0].textContent = "郵便番号です"; } else { //郵便番号以外 obj[0].textContent = "郵便番号ではありません"; } } </script> <body> <div class="main"> <h2><span class="badge badge-success">判定結果</span></h2> <form> <div class="form-group"> <label for="formGroupExampleInput" class="bmd-label-floating">文字列</label> <input id="str" type="text" class="form-control"> </div> </form> <button onclick="hoge()" type="button" class="btn btn-raised btn-danger"> 判定 </button> </div> </body> </html> |
判定されていることが確認できます。

-
前の記事
javascript canvasタグに画像を入れる 2020.09.29
-
次の記事
javascript canvasタグに円や半円を描画する 2020.09.29
コメントを書く