jQuery Validatede 結合Ajax 表單驗證提交
阿新 • • 發佈:2022-02-22
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>新增</title> <link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap.min.css"> </head> <body> <form action="" method="get" id="signupForm" style="width: 300px"> <div class="form-group"> <label for="name">賬號</label> <input type="text" class="form-control" id="username" name="username" placeholder="請輸入賬號"> <label class="error">提示資訊</label> </div> <div class="form-group"> <label for="name">密碼</label> <input type="password" class="form-control" id="password" name="password" placeholder="請輸入密碼"> <label class="error">提示資訊</label> </div> <div class="form-group"> <label for="name">確認密碼</label> <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="請輸入密碼"> <label class="error">提示資訊</label> </div> <button type="submit" class="btn btn-primary">新增</button> </form> </body> </html> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"> </script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script> $("#signupForm").validate({ onsubmit: true,// 是否在提交是驗證 onfocusout: false,// 是否在獲取焦點時驗證 onkeyup: false,// 是否在敲擊鍵盤時驗證 rules: { username: { required: true, minlength: 2 }, password: { required: true, minlength: 5 }, confirm_password: { required: true, minlength: 5, equalTo: "#password" }, }, messages: { username: { required: "請輸入使用者名稱", minlength: "使用者名稱必需由兩個字元組成", }, password: { required: "請輸入密碼", minlength: "密碼長度不能小於 5 個字元" }, confirm_password: { required: "請輸入密碼", minlength: "密碼長度不能小於 5 個字元", equalTo: "兩次密碼輸入不一致" } }, errorPlacement: function(error, element) { error.appendTo(element.parent()); }, submitHandler:function (form) { //進行ajax傳值 $.ajax({ url : "{:url('/exam1/save')}", type : "post", dataType : "json", data: { user: $("#username").val(), password: $("#password").val() }, success : function(msg) { //要執行的程式碼 console.log(msg) } }); } }) </script>
控制器:
public function save(Request $request) { // $data=$request->post(); return json(['code'=>200,'message'=>'sucess','data'=>$data]); }