---
# System prepended metadata

title: jQuery 驗證表單
tags: [jQuery, JavaScript]

---

# jQuery 驗證表單

###### tags: `jQuery` `JavaScript`

---
## JS驗證程式碼
>可參考正規表示法:[正規表示式 Regular Expression](https://poychang.github.io/note-regular-expression/)

#### .val()
多用於&lt;input&gt;格式
1、通常被用於input、select、textarea
2、通常回傳該元素的內文或是設置值
3.如果該方法未設置參數，則返回被選元素的值。

#### .submit()
當提交表單時，會發生submit事件。

#### Event.preventDefault()
* 如果事件可以被取消，就取消事件（即取消事件的預設行為）。但不會影響事件的傳遞，事件仍會繼續傳遞。
* 常用於點及按鈕時阻止表單提交

範例:
```javascript=
<script>
    $("#validationForm").submit(function(event){
        var errorMessage = "";
        event.preventDefault();
        var name = $("#email-name").val();
        var email = $("#email-address").val();
        var tel = $("#email-tel").val();
        var issue = $("#mail-issue").val();
        var date = $("email-date").val();
        var message = $("#mail-message").val();
        function is_valid_email_address(emailAddress){
            var pattern = /^\b[A-Z0-9-]+@[A-Z0-9]+\.com\b/i;
            return pattern.test(emailAddress);
        }
        function is_valid_tel(telephone){
            var pattern = /^09\d{2}-?\d{3}-?\d{3}$/;
            return pattern.test(telephone);
        }
    if (name == "" || tel == "" || message == ""){
        errorMessage = "請輸入完整資訊";
    } else if (!is_valid_email_address(email)){
        errorMessage = "請輸入格式正確的電子郵件地址";
    } else if (!is_valid_tel(tel)){
        errorMessage = "請輸入格式正確的電話";
    }
    if ( errorMessage == ""){
        $("#error").html("郵件已發送!");
        $("#error").css("color","green");
    } else{
        $("#error").html(errorMessage);
        $("#error").css("color","red");
    }
    });
</script>
```

可以設定顯示在文字框下方的提示

==小技巧:id屬性用JS替換代入文字， div class包住頭尾寫一個padding-bottom==
下面這個實作用#emailError
```
if (is_valid_email_address(email)){
        $("#emailError").text("");
        $("#emailError").css("color","green");
    }
```
```
<div class="input-bum">
            <label for="email-address">電子郵件</label>
            <input id="email-address" type="text" name="email" placeholder="abc123@mail.com" maxlength="80" class="input-width"><br>
            <span id="emailError"></span>
        </div>
```
實際樣式如下:
 <iframe height="265" style="width: 100%;" scrolling="no" title="mdyxOwq" src="https://codepen.io/rorobioao/embed/mdyxOwq?height=265&theme-id=default&default-tab=css,result" frameborder="no" allowtransparency="true" allowfullscreen="true">
  See the Pen <a href='https://codepen.io/rorobioao/pen/mdyxOwq'>mdyxOwq</a> by Tina
  (<a href='https://codepen.io/rorobioao'>@rorobioao</a>) on <a href='https://codepen.io'>CodePen</a>.
</iframe>
 
 下面詳細程式碼↓
:::spoiler

JS
```javascript=
<script>
    $("#validationForm").submit(function(event){
        var errorMessage = "";
        event.preventDefault();
        var name = $("#email-name").val();
        //設定變數name 是 標籤$("#email-name")的值
        var email = $("#email-address").val();
        var tel = $("#email-tel").val();
        var issue = $("#mail-issue").val();
        var date = $("email-date").val();
        var message = $("#mail-message").val();
        function is_valid_email_address(emailAddress){
            var pattern = /^\b[A-Z0-9-]+@[A-Z0-9]+\.com\b/i;
            return pattern.test(emailAddress);
            //設定變數pattern 是 (pattern的驗證格式)
            //回傳 替換文字內容emailAddress的值
        }
        function is_valid_tel(telephone){
            var pattern = /^09\d{2}-?\d{3}-?\d{3}$/;
            return pattern.test(telephone);
        }
    if (name == "" || tel == "" || message == ""){
        errorMessage = "請輸入完整資訊";
        //如果 name 或 tel 或 message 的值是空的，執行 errorMessage
    } else if (!is_valid_email_address(email)){
        errorMessage = "請輸入格式正確的電子郵件地址";
        $("#emailError").text(errorMessage);
        $("#emailError").css("color","red");
    } else if (!is_valid_tel(tel)){
        errorMessage = "請輸入格式正確的電話";
        $("#telError").text(errorMessage);
        $("#telError").css("color","red");
    }
    if (is_valid_email_address(email)){
        $("#emailError").text("");
        $("#emailError").css("color","green");
    }
    if (is_valid_tel(tel)){
        $("#telError").text("");
    }
    if ( errorMessage == ""){
        $("#error").html("郵件已發送!");
    } else{
        $("#error").html(errorMessage);
        $("#error").css("color","red");
    }
    });
</script>
```
HTML
```htmlmixed=
<div id="container1">
    <div>
        <h4>請留下您的訊息，我們會盡快與您聯絡。</h4>
    </div>
    <form action="" id="validationForm">
        <div class="input-bum">
            <label for="email-name">姓　　名*</label>
            <input id="email-name" type="text" name="name" placeholder="請輸入您的姓名" class="input-width" maxlength="30" autofocus required>
        </div>
        <div class="input-bum">
            <label for="email-address">電子郵件</label>
            <input id="email-address" type="text" name="email" placeholder="abc123@mail.com" maxlength="80" class="input-width"><br>
            <span id="emailError"></span>
        </div>
        <div class="input-bum">
            <label for="email-tel">連絡電話*</label>
            <input id="email-tel" type="tel" name="email-tel" placeholder="0912345678" maxlength="10" class="input-width"required><br>
            <span id="telError"></span>
        </div>

        <label for="mail-issue">諮詢類型</label>
            <select id="mail-issue" name="gender">
                <option value="issue01">購買相關</option>
                <option value="issue02">產品操作</option>
                <option value="issue03">退換貨問題</option>
                <option value="issue04">合作提案</option>
            </select>
        <label for="email-date">發生日期</label>
            <input id="email-date" type="date" name="date" class="input-width">

            <textarea name="message" id="mail-message" cols="30" rows="10" placeholder="詳細內容*" required></textarea>	
        <button id="submitButton" type="submit" name="submit">發送郵件</button>
    </form>
</div>	
<div id="error"></div>
```







---
<style>
h2 {
    color: #2383F8;
}
h3 {
    color: #1AA340;
}
h4 {
    color: white;
    background-color: #1B3686;
    padding:8px;
}

.code1 {
    padding: 2px 4px;
    font-size: 90%;
    color: #c7254e;
    background-color: #344D95;
    border-radius: 4px;
    font-family:'Fira Code';
}
.code {
    padding: 2px 4px;
    font-size: 90%;
    font-family:'Fira Code';
}
</style>
:::