validate+jquery+ajax表單驗證

1.案例

?

1.1 Html form表單內容

復制代碼
<form class="cForm" id="cForm" method="post" action="">
<p>
<label for="user">用戶名</label>
<input id="user" name="user" required minlength="3">
</p>
<p>
<label for="password">密碼</label>
<input id="password" type="password" maxlength="12" name="password">
</p>
<p>
<input class="submit" type="submit" value="登錄">
</p>
</form>
復制代碼

?

1.2 js代碼(進行表單自驗證)

復制代碼
<script>$().ready(function() {$("#cForm").validate({onsubmit:true,// 是否在提交是驗證onfocusout:false,// 是否在獲取焦點時驗證onkeyup :false,// 是否在敲擊鍵盤時驗證

rules: {    //規則user: {  //要對應相對應的input中的name屬性required: true},password: {required: true}
},
messages:{    //驗證錯誤信息
  user: {required: "請輸入用戶名"},password: {required: "請輸入密碼"}
},
submitHandler: function(form) { //通過之后回調
//進行ajax傳值
$.ajax({url : "{:U('user/index')}",type : "post",dataType : "json",data: {user: $("#user").val(),password: $("#password").val() },success : function(msg) {//要執行的代碼
  }
});
},
invalidHandler: function(form, validator) {return false;}
}); 
});</script>
復制代碼

?

1.3在控制器中對ajax傳遞的數據進行處理

? ? ?把ajax傳到控制器中的數據進行處理,返回結果。

?

1.4效果展示

  

?

?

?

2.validate的一些驗證參數

?

2.1使用表單自驗證可以通過導入js庫

<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>

可在官網進行下載

?

默認的校驗規則

序號 規則 描述
1 required:true 必須輸入的字段。
2 remote:"check.php" 使用 ajax 方法調用 check.php 驗證輸入值。
3 email:true 必須輸入正確格式的電子郵件。
4 url:true 必須輸入正確格式的網址。
5 date:true 必須輸入正確格式的日期。日期校驗 ie6 出錯,慎用。
6 dateISO:true 必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22。只驗證格式,不驗證有效性。
7 number:true 必須輸入合法的數字(負數,小數)。
8 digits:true 必須輸入整數。
9 creditcard: 必須輸入合法的信用卡號。
10 equalTo:"#field" 輸入值必須和 #field 相同。
11 accept: 輸入擁有合法后綴名的字符串(上傳文件的后綴)。
12 maxlength:5 輸入長度最多是 5 的字符串(漢字算一個字符)。
13 minlength:10 輸入長度最小是 10 的字符串(漢字算一個字符)。
14 rangelength:[5,10] 輸入長度必須介于 5 和 10 之間的字符串(漢字算一個字符)。
15 range:[5,10] 輸入值必須介于 5 和 10 之間。
16 max:5 輸入值不能大于 5。
17 min:10 輸入值不能小于 10。

?

2.2將校驗規則寫到 js 代碼中

就像我上面寫的例子,直接把驗證規則和提示信息寫在js代碼中

復制代碼
$().ready(function() {
// 在鍵盤按下并釋放及提交后驗證提交表單$("#signupForm").validate({rules: {firstname: "required",lastname: "required",username: {required: true,minlength: 2},password: {required: true,minlength: 5},confirm_password: {required: true,minlength: 5,equalTo: "#password"},email: {required: true,email: true},topic: {required: "#newsletter:checked",minlength: 2},agree: "required"},messages: {firstname: "請輸入您的名字",lastname: "請輸入您的姓氏",username: {required: "請輸入用戶名",minlength: "用戶名必需由兩個字母組成"},password: {required: "請輸入密碼",minlength: "密碼長度不能小于 5 個字母"},confirm_password: {required: "請輸入密碼",minlength: "密碼長度不能小于 5 個字母",equalTo: "兩次密碼輸入不一致"},email: "請輸入一個正確的郵箱",agree: "請接受我們的聲明",topic: "請選擇兩個主題"}
});
復制代碼

?校驗規則中的名字必須與input中的name值對應

?

2.3常用方法及注意問題

?

2.3.1我們可以用其他方式替代默認的 submit

復制代碼
$().ready(function() {$("#signupForm").validate({submitHandler:function(form){  //表單提交后要執行的內容
            form.submit();}    });
});
復制代碼

  使用ajax ? //跟我上面的ajax傳值差不多

 $(".selector").validate({     submitHandler: function(form) {      $(form).ajaxSubmit();     }  })

?

2.3.2debug,只驗證不提交表單

$().ready(function() {$("#signupForm").validate({debug:true});
});

如果一個頁面中有多個表單都想設置成為 debug,則使用:

$.validator.setDefaults({debug: true
})

?

2.3.3ignore:忽略某些元素不驗證

ignore: ".ignore"

?

2.3.4更改錯誤信息顯示的位置

errorPlacement:Callback

指明錯誤放置的位置,默認情況是:error.appendTo(element.parent());即把錯誤信息放在驗證的元素后面。

errorPlacement: function(error, element) {  error.appendTo(element.parent());  
}

?

2.3.5更改錯誤信息顯示的樣式

設置錯誤提示的樣式,可以增加圖標顯示,在該系統中已經建立了一個 validation.css,專門用于維護校驗文件的樣式。

復制代碼
input.error { border: 1px solid red; }
label.error {background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;padding-left: 16px;padding-bottom: 2px;font-weight: bold;color: #EA5200;
}
label.checked {background:url("./demo/images/checked.gif") no-repeat 0px 0px;
}
復制代碼

?

2.3.6每個字段驗證通過執行函數

success: function(label) {// set &nbsp; as text for IElabel.html("&nbsp;").addClass("checked");//label.addClass("valid").text("Ok!")
}

?

2.3.7驗證的觸發方式修改

觸發方式 類型 描述 默認值
onsubmit Boolean 提交時驗證。設置為 false 就用其他方法去驗證。 true
onfocusout Boolean 失去焦點時驗證(不包括復選框/單選按鈕)。 true
onkeyup Boolean 在 keyup 時驗證。 true
onclick Boolean 在點擊復選框和單選按鈕時驗證。 true
focusInvalid Boolean 提交表單后,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點。 true
focusCleanup Boolean 如果是 true 那么當未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用。 false

?重置表單 很實用
復制代碼
$().ready(function() {var validator = $("#signupForm").validate({submitHandler:function(form){alert("submitted");   form.submit();}    });$("#reset").click(function() {validator.resetForm();});});
復制代碼

?

2.3.8異步驗證

使用 ajax 方式進行驗證,默認會提交當前驗證的值到遠程地址,如果需要提交其他的值,可以使用 data 選項。

復制代碼
remote: {url: "check-email.php",     //后臺處理程序type: "post",               //數據發送方式dataType: "json",           //接受數據格式   data: {                     //要傳遞的數據username: function() {return $("#username").val();}}
}
復制代碼

?

2.3.9添加自定義校驗

addMethod:name, method, message

自定義驗證方法

復制代碼
// 中文字兩個字節
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {var length = value.length;for(var i = 0; i < value.length; i++){if(value.charCodeAt(i) > 127){length++;}}return this.optional(element) || ( length >= param[0] && length <= param[1] );   
}, $.validator.format("請確保輸入的值在{0}-{1}個字節之間(一個中文字算2個字節)"));// 郵政編碼驗證   
jQuery.validator.addMethod("isZipCode", function(value, element) {   var tel = /^[0-9]{6}$/;return this.optional(element) || (tel.test(value));
}, "請正確填寫您的郵政編碼");
復制代碼

?

2.3.10radio 和 checkbox、select 的驗證

?

列舉一個demo統一驗證一下

復制代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Validate radio(單選按鈕)、checkbox(復選按鈕)和 select(下拉框)</title><link rel="stylesheet" media="screen" href="http://static.runoob.com/assets/jquery-validation-1.14.0/demo/css/screen.css">
<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 src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script><style>
.block { display: block; }
form.cmxform label.error { display: none; }
</style></head>
<body><div id="main"><form class="cmxform" id="form1" method="get" action=""><fieldset><legend>通過 radio(單選按鈕)和 checkbox(復選按鈕)驗證表單</legend><fieldset><legend>性別</legend><label for="gender_male"><input  type="radio" id="gender_male" value="m" name="gender" required>男性</label><label for="gender_female"><input  type="radio" id="gender_female" value="f" name="gender">女性</label><label for="gender" class="error">請選擇您的性別。</label></fieldset><fieldset><legend>婚姻狀況</legend><label for="family_single"><input  type="radio" id="family_single" value="s" name="family" required>單身</label><label for="family_married"><input  type="radio" id="family_married" value="m" name="family">已婚</label><label for="family_other"><input  type="radio" id="family_other" value="o" name="family">其他</label><label for="family" class="error">您選擇您的婚姻狀況。</label></fieldset><p><label for="agree">請同意我們的條款</label><input type="checkbox" class="checkbox" id="agree" name="agree" required><br><label for="agree" class="error block">請同意我們的條款!</label></p><fieldset><legend>垃圾郵件</legend><label for="spam_email"><input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required minlength="2">垃圾郵件 - E-Mail</label><label for="spam_phone"><input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]">垃圾郵件 - Phone</label><label for="spam_mail"><input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]">垃圾郵件 - Mail</label><label for="spam[]" class="error">請選擇至少兩種類型的垃圾郵件。</label></fieldset><p><input class="submit" type="submit" value="提交"></p></fieldset>
</form><form id="selecttest"><h2>一些關于 select 的測試</h2><p><label for="jungle">請選擇一個叢林名詞</label><br><select id="jungle" name="jungle" title="請選擇一個叢林名詞!" required><option value=""></option><option value="1">Buga</option><option value="2">Baga</option><option value="3">Oi</option></select></p><p><label for="fruit">請選擇至少兩種水果</label><br><select id="fruit" name="fruit" title="請選擇至少兩種水果!" required minlength="2" multiple="multiple"><option value="b">Banana</option><option value="a">Apple</option><option value="p">Peach</option><option value="t">Turtle</option></select></p><p><label for="vegetables">請選擇不超過兩種蔬菜</label><br><select id="vegetables" name="vegetables" title="請選擇不超過兩種蔬菜!" required maxlength="2" multiple="multiple"><option value="p">Potato</option><option value="t">Tomato</option><option value="s">Salad</option></select></p><p><label for="cars">請選擇至少兩種但不超過三種汽車</label><br><select id="cars" name="cars" title="請選擇至少兩種但不超過三種汽車!" required rangelength="[2,3]" multiple="multiple"><option value="m_sl">Mercedes SL</option><option value="o_c">Opel Corsa</option><option value="vw_p">VW Polo</option><option value="t_s">Titanic Skoda</option></select></p><p><input type="submit" value="Validate Select 測試"></p>
</form></div></body>
</html>
復制代碼

js代碼

復制代碼
<script>
$.validator.setDefaults({submitHandler: function() {alert("submitted!");}
});$(document).ready(function() {$("#form1").validate();$("#selecttest").validate();
});
</script>
復制代碼

?

大家有什么意見或者建議可以留言指導、批評

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/247685.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/247685.shtml
英文地址,請注明出處:http://en.pswp.cn/news/247685.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Html5做webapp中界面適配的問題總結

做一款軟件首先是要做出相應的界面&#xff0c;然而對于手機軟件開發者來說&#xff0c;大小各異的手機屏幕卻給我們帶來了不少的麻煩。HTML5技術在大家的心中要比傳統的Android/iOS/wp簡單的多&#xff0c;因為它的適配性和平臺跨越方面比較出色。在外看來卻不是那樣的&#x…

設置Maven下載鏡像源(直接替換其中的 settings.xml 內容即可)

<?xml version"1.0" encoding"UTF-8"?> <settings xmlns"http://maven.apache.org/SETTINGS/1.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/SETTINGS/1.0.…

P1576 最小花費

----------------------------------- 這道題就是圖論最短路&#xff0c;但是我們要改一下一些細節 比如說&#xff0c;因為這是算匯率&#xff0c;我們的初始化就要是0 我們還要改一改松弛操作 ----------------------------------- 還有&#xff0c;題目上給的是匯率&#xf…

css hack技術整理

做前端多年&#xff0c;雖然不是經常需要hack&#xff0c;但是我們經常會遇到各瀏覽器表現不一致的情況。基于此&#xff0c;某些情況我們會極不情愿的使用這個不太友好的方式來達到大家要求的頁面表現。我個人是不太推薦使用hack的&#xff0c;要知道一名好的前端&#xff0c;…

Hanoi雙塔問題

Hanoi雙塔問題 題目描述 給定A,B,C三根足夠長的細柱&#xff0c;在A柱上放有2n個中間有空的圓盤&#xff0c;共有n個不同的尺寸&#xff0c;每個尺寸都有兩個相同的圓盤&#xff0c;注意這兩個圓盤是不加區分的(下圖為n3的情形&#xff09;。現要將 這些國盤移到C柱上&#xff…

vue中config/index.js:配置的詳細理解

當我們需要和后臺分離部署的時候&#xff0c;必須配置config/index.js: 用vue-cli 自動構建的目錄里面 &#xff08;環境變量及其基本變量的配置&#xff09; 123456789101112131415var path require(path)module.exports {build: {index: path.resolve(__dirname, dist/ind…

uni-app吸頂固定樣式

<template><view class"full"><view class"sticky-box"><!-- 搜索 --><uni-search-bar class"unisearchbar" radius"5" placeholder"請輸入搜索關鍵詞" clearButton"auto" bgColor&qu…

Django(模板語言-自定義filter和simple_tag)

filter過濾器的主要形式&#xff1a;變量|函數,意思是將變量交給函數處理&#xff0c;而自定義filter就是自己定義函數&#xff0c;因為用到已有的很少。 1.在當前app中創建templatetags模塊(包&#xff1a;帶__init__.py)&#xff08;必須的&#xff09; 2.在templatetags中創…

uni-app商品分類

<template><view class"classify"><!-- 分類部分 --><view class"cate-left"><view :class"[cate-item,activeIndexindex?active:]" v-for"(item,index) in cateList" :key"index"click"c…

10分鐘看懂瀏覽器的渲染過程及優化

一、瀏覽器概述 目前的主流瀏覽器有5個&#xff1a;Internet Explorer、Firefox、Safari、Chrome和Opera瀏覽器。根據 StatCounter 瀏覽器統計數據&#xff0c;目前&#xff08;截止2019 年 5 月&#xff09;Firefox、Safari 和 Chrome 瀏覽器的總市場占有率將近 83.66%。由此可…

淺談 Vue 項目優化

前幾天看到大家說 vue 項目越大越難優化&#xff0c;帶來很多痛苦&#xff0c;這是避免不了的&#xff0c;問題終究要解決&#xff0c;框架的性能是沒有問題的&#xff0c;各大測試網站都有相關數據。下面進入正題 基礎優化 所謂的基礎優化是任何 web 項目都要做的&#xff0c;…

uni-app微信小程序一鍵登錄獲取權限功能

<button class"bottom size_30" type"primary" lang"zh_CN" click"getUserInfo">一鍵登錄</button>//第一授權獲取用戶信息》按鈕觸發getUserInfo() {// 展示加載框uni.showLoading({title: 加載中,});uni.getUserProfile…

第九章 結構體與共用體

姓名&#xff1a;呂家浩 實驗地點&#xff1a;教學樓514教室 實驗時間&#xff1a;4月30日 一、本章要點 1.通過實驗理解結構體和共用體的數據結構2.結構體、共用體中數組的使用及變量的賦值3.結構體和共用體定義時的嵌套使用&#xff08;嵌套使用的結構體必須先定義&…

H5-localStorage數據存儲總結

一、什么是localStorage、sessionStorage 在HTML5中&#xff0c;新加入了一個localStorage特性&#xff0c;這個特性主要是用來作為本地存儲來使用的&#xff0c;解決了cookie存儲空間不足的問題(cookie中每條cookie的存儲空間為4k)&#xff0c;localStorage中一般瀏覽器支持的…

正則校驗與時間格式化

// 日期回顯 export function formatTime(data&#xff0c;fametYYYY-MM-DD HH:MMM:SS) {if(famet YYYY-MM-DD HH:MMM:SS){const time new Date(data)const year time.getFullYear()const month time.getMonth() 1const day time.getDate()const hour time.getHours()co…

CometOJ#6 雙倍快樂(簡單DP)

鏈接&#xff1a;https://www.cometoj.com/contest/48/problem/B 題意&#xff1a;給出一串數列&#xff0c;要求在這個數列中找出兩條“不相交”的非下降子序列使得子序列之和最大。“不相交”即不存在任意的ai同時存在于兩個子序列中。 分析&#xff1a;筆者刷題量不多&#…

iOS開發-證書問題精析~

在iOS開發過程中&#xff0c;不可避免的要和證書打交道&#xff0c;真機調試、App上架、打包給測試去測試等都需要搞證書。在此過程中我們會遇到很多的問題&#xff0c;但是如果掌握了真機調試的原理和本質&#xff1b;遇到問題&#xff0c;我們就更容易定位問題之所在&#xf…

selenium+Java自動化

轉載于:https://www.cnblogs.com/arvin-feng/p/11110483.html

html 5 本地數據庫(Web Sql Database)

基于HTML5的Web DataBase 可以讓你在瀏覽器中進行數據持久地存儲管理和有效查詢&#xff0c;假設你的離線應用程序有需要規范化的存儲功能 本文講述如何使用核心方法openDatabase、transaction、executeSql 1.新建一個網頁&#xff0c;比如&#xff1a;test.html 內容如下&am…

前端學習資料及路線名稱網站

IT前端學習資料及路線常用PC端UI組件庫餓了么(Element-UI)https://element.eleme.cn/#/zh-CN常用小程序端UI組件庫uView UIhttp://v1.uviewui.com/名稱網站JQuery文件網https://code.jquery.com/jquery/jQuery手冊&#xff08;pc端&#xff09;http://jquery.cuishifeng.cn/jQu…