文字列から任意の文字を検索する

郵便番号が正しく入力されているか調べる

<h2>文字列から任意の文字を検索する</h2>
<form name="mapForm" id="mapForm" method="get" action="./map.cgi">
郵便番号:<input type="text" size="16" name="postalCode" id="postalCode"><br>
<input type="submit" value="住所登録">
</form>
(function(){
    //イベントとイベントハンドラを設定する
    if (window.addEventListener) window.addEventListener("load", searchText, true);
    if (window.attachEvent) window.attachEvent("onload", searchText);
    function searchText(){
        document.getElementById("mapForm").onsubmit = function(){
            var userAddress = document.getElementById("postalCode").value;
            //正規表現を使って〒XXX-XXXXの形式になっているか調べる、マッチしない場合はnullを返す
            var matchText = userAddress.match(/〒\d\d\d-\d\d\d\d$/);
            if (matchText == null){
                alert("住所は〒XXX-XXXXの形式で入れてください");
                return false;
            }else{
                return true;
            }
        }
    }
})();