如何使用 jQuery 來驗證表單?


首先,你必須製作一個HTML 表單,如下所示。

<html>
<body>
<h2>Validation of a form</h2>
<form id="form" method="post" action="">
First name:<br>
<input type="text" name="firstname" value="john">
<br>
Last name:<br>
<input type="text" name="lastname" value="Doe">
<br>
Email:<br>
<input type="email" name="u_email" value="johndoe@gmail.com">
<br>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

現在使用 jQuery 驗證外掛以更簡單的方式驗證表單資料。

首先,在你的檔案中新增 jQuery 庫。

<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
then add javascript code:
$(document).ready(function() {
   $("#form").validate();
});
</script>

然後使用簡單的語法定義規則。

jQuery(document).ready(function() {
   jQuery("#forms).validate({
      rules: {
         firstname: 'required',
         lastname: 'required',
         u_email: {
            required: true,
            email: true,//add an email rule that will ensure the value entered is valid email id.
            maxlength: 255,
         },
      }
   });
});

定義錯誤訊息。

messages: {
   firstname: 'This field is required',
   lastname: 'This field is required',
   u_email: 'Enter a valid email',
},

最後,提交表單。

submitHandler: function(form) {
   form.submit();
}

更新時間: 2023 年 9 月 9 日

31K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

立刻開始
廣告
© . All rights reserved.