❶ Jquery.validate.js實現前端表單驗證
jquery.validate.js表單驗證
官方網站: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
API: http://jquery.bassistance.de/api-browser/plugins.html
當前版本:1.5.5
需要JQuery版本:1.2.6+, 兼容 1.3.2
<script src="../js/jquery.js" type="text/javascript"></script>
<script src="../js/jquery.validate.js" type="text/javascript"></script>
(1)required:true 必輸欄位
(2)remote:"check.php" 使用ajax方法調用check.php驗證輸入值
(3)email:true 必須輸入正確格式的電子郵件
(4)url:true 必須輸入正確格式的網址
(5)date:true 必須輸入正確格式的日期
(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
例子:自定義密碼驗證的規則
❷ javascript 怎麼實現即時驗證表單信息
很簡單的,一般是利用onchange="chk1()",然後利用的是值一發生改變就會調用chk1的事件,而該事件就是對其值進行驗證的,但對於用戶的驗證,往往還要採用AJAX中的XMLHTTP進行驗證,這個涉及伺服器的知道,也可以想辦法實現!
❸ validation 的js是做什麼用的
jQuery.validationEngine plugin是一個旨在校驗表單元素的javascript插件。目前在IE6-8、Chrome、Firefox、Safari、Opera等瀏覽器上表現良好。比如校驗我們常見的Email、phone、URL等等,對於負責的Ajax調用校驗也提供了支持。而且提示信息也可支持多種語言。現在已經發展到了v2.6.2我們可以在github上很輕松的獲取到它的源碼。
一下是自己寫的一個小例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery.validationEngine plugin Demo</title>
<link type="text/css"rel="stylesheet"href="/static/css/jquery.validation/validationEngine.jquery.css"/>
<script type="text/javascript"src="/static/js/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript"src="/static/js/jquery.validation/jquery.validationEngine-zh_CN.js"></script>
<script type="text/javascript"src="/static/js/jquery.validation/jquery.validationEngine.js"></script>
<script type="text/javascript">
$(function(){
var form ="myForm";
var condition = [
{name:"username",rule:"validate[required,maxSize[5]]"} ,
{name:"password",rule:"validate[required] text-input"} ,
{name:"url",rule:"validate[required,custom[url]]"},
{name:"letter",rule:"validate[required,custom[onlyLetterNumber]]"},
{name:"date",rule:"validate[required,custom[date]]"}
];
validationInit(condition,form);
$("#sub").click(function(){
console.log("validationform="+$("#"+form).validationEngine('validate'));
if($("#"+form).validationEngine()){
return;
}
myForm.submit();
});
});
function validationInit(condition,form){
for(var i = 0; i < condition.length; i++){
var cond = condition[i];
$("#"+form+"[name="+cond.name+"]").attr("class",cond.rule);
}
$("#"+form).validationEngine('attach',{
}).css({border:"2px solid #000"});
}
</script>
</head>
<body>
<div style="padding-top: 100px">
<form action=""id="myForm"name="myForm"method="post">
username:<input type="text"name="username"id="username"/><br/>
password:<input type="text"name="password"id="password"data-prompt-position="bottomLeft:20px"/><br/>
url:<input type="text"id="url"name="url"value="http://"/><br/>
only letter:<input type="text"id="letter"name="letter"value="too many spaces obviously"/><br/>
date:<input type="text"id="date"name="date"value=""/><br/>
<input type="button"value="提交"id="sub"/>
</form>
</div>
</body>
</html>
可以看出使用了jquery.validationEngine plugin之後頁面的校驗js代碼變得更加整潔了。
除了上述用法,jquery.validationEngine也可以作用在某個表單元素上
$("#form.id").validationEngine();
或
$("#form.id").validationEngine(action or options);
validationEngine的幾個基本action:
attach:綁定表單驗證
detach:解除表單驗證
validate:驗證控制項或表單 返回ture or false
showPrompt:在某個元素上創建一個提示,3中狀態『pass』,『error』,'load'
hide:隱藏對應元素及元素內的提示信息
hideAll:隱藏頁面上的所有提示
updatePromptsPosition:更新提示層的位置
從
$("#"+form).validationEngine('attach',{
}).css({border:"2px solid #000"});
可以看出validationEngine方法支持鏈式調用。
validationEngine的3中自定義事件
jqv.form.validating:$("#form").bind("jqv.form.validating",function(event){});表單驗證時事件
jqv.form.result:$("#form").bind("jqv.form.result",function(event,errorFound){});表單驗證完成時事件 errorFound:表單驗證不通過(true或false)
jqv.field.result:$("#form").bind("jqv.field.result",function(event,field,isError,promptText){});單個控制項驗證完成時事件,field 控制項對象,isError:控制項驗證不通過(true或false)promptText: 提示信息
HTML5屬性
屬性名 描述
data-validation-engine 設置驗證規則,除了class驗證的另一種選擇
data-validation-placeholder 佔位符 當為必填控制項驗證時值不能為空 也不能為佔位符
data-prompt-position 自定義提示信息的位置,可設置為:"topRight","topLeft","bottomRight""bottomLeft","centerRight","centerLeft","inline"可設置更具體的位置,格式為:"方向:X偏移值,Y偏移值"。如:data-prompt-position="bottomLeft:20,5"PS:偏移值可以為負數
data-prompt-target 載入提示信息的容器,值為元素的id 僅在promptPosition或data-prompt-position設置為」inline「時有效
jquery.validationEngine默認屬性值
// LEAK GLOBAL OPTIONS
$.validationEngine= {fieldIdCounter: 0,defaults:{
// 觸發控制項校驗的事件名稱
validationEventTrigger:"blur",
// 自動滾動視窗到第一個錯誤位置
scroll: true,
// 為第一個input框聚焦
focusFirstField:true,
// 是否提示信息
showPrompts: true,
// 是否驗證不可見元素(如type="hidden"的輸入框)
validateNonVisibleFields: false,
// 用特殊class屬性值 來忽略校驗控制項
ignoreFieldsWithClass: 'ignoreMe',
// Opening box position, possible locations are: topLeft,
// topRight, bottomLeft, centerRight, bottomRight, inline
// inline gets inserted after the validated field or into an element specified in data-prompt-target
//提示信息的位置設定
promptPosition:"topRight",
bindMethod:"bind",
// internal, automatically set to true when it parse a _ajax rule
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
//是否使用Ajax提交表單 默認是get方式
ajaxFormValidation: false,
// The url to send the submit ajax validation (default to action) //設置Ajax提交的url 默認為form的action
ajaxFormValidationURL: false,
// HTTP method used for ajax validation
//設置Ajax表單提交時使用的數據傳輸方式
ajaxFormValidationMethod: 'get',
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
//表單提交,Ajax驗證完成後的行為
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel //表單提交驗證通過後 Ajax提交之前的回調函數
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function assiciated with it
onValidationComplete: false,
// Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages
doNotShowAllErrosOnSubmit: false,
// Object where you store custom messages to override the default error messages
custom_error_messages:{},
// true if you want to validate the input fields on blur event
binded: true,
// set to true if you want to validate the input fields on blur only if the field it's not empty
notEmpty: false,
// set to true, when the prompt arrow needs to be displayed
showArrow: true,
// set to false, determines if the prompt arrow should be displayed when validating
// checkboxes and radio buttons
showArrowOnRadioAndCheckbox: false,
// did one of the validation fail ? kept global to stop further ajax validations
isError: false,
// Limit how many displayed errors a field can have
maxErrorsPerField: false,
// Caches field validation status, typically only bad status are created.
// the array is used ring ajax form validation to detect issues early and prevent an expensive submit
ajaxValidCache: {},
// Auto update prompt position after window resize
autoPositionUpdate: false,
InvalidFields: [],
onFieldSuccess: false,
onFieldFailure: false,
onSuccess: false,
onFailure: false,
validateAttribute:"class",
addSuccessCssClassToField:"",
addFailureCssClassToField:"",
// Auto-hide prompt
autoHidePrompt: false,
// Delay before auto-hide
autoHideDelay: 10000,
// Fade out ration while hiding the validations
fadeDuration: 0.3,
// Use Prettify select library
prettySelect: false,
// Add css class on prompt
addPromptClass :"",
// Custom ID uses prefix
usePrefix:"",
// Custom ID uses suffix
useSuffix:"",
// Only show one message per error prompt
showOneMessage: false
❹ 如何在form中調用js表單驗證
|比如有個表單
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
js驗證函數:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
當提交表單的回時候就會觸答發驗證,運行結果:
❺ 帶表單的javascript驗證身份證號
其實就是加一個JS函數段吧。下面這段JS腳本是我用過的最完善的身份證號的驗證程序了,因為只有真正的身份證號才能被通過,你可以試的。直接復制運行。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Check card no</title>
<script type='text/javascript'>
/*
Author:yufulong
Blog:http://www.xiaoxiaozi.com
*/
var vcity={ 11:"北京",12:"天津",13:"河北",14:"山西",15:"內蒙古",
21:"遼寧",22:"吉林",23:"黑龍江",31:"上海",32:"江蘇",
33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山東",41:"河南",
42:"湖北",43:"湖南",44:"廣東",45:"廣西",46:"海南",50:"重慶",
51:"四川",52:"貴州",53:"雲南",54:"西藏",61:"陝西",62:"甘肅",
63:"青海",64:"寧夏",65:"新疆",71:"台灣",81:"香港",82:"澳門",91:"國外"
};
checktheform = function()
{
var card = document.getElementById('card_no').value;
//是否為空
if(card === '')
{
alert('請輸入身份證號,身份證號不能為空');
document.getElementById('card_no').focus;
return false;
}
//校驗長度,類型
if(isCardNo(card) === false)
{
alert('您輸入的身份證號碼不正確,請重新輸入');
document.getElementById('card_no').focus;
return false;
}
//檢查省份
if(checkProvince(card) === false)
{
alert('您輸入的身份證號碼不正確,請重新輸入');
document.getElementById('card_no').focus;
return false;
}
//校驗生日
if(checkBirthday(card) === false)
{
alert('您輸入的身份證號碼生日不正確,請重新輸入');
document.getElementById('card_no').focus();
return false;
}
//檢驗位的檢測
if(checkParity(card) === false)
{
alert('您的身份證校驗位不正確,請重新輸入');
document.getElementById('card_no').focus();
return false;
}
alert('OK');
return true;
};
//檢查號碼是否符合規范,包括長度,類型
isCardNo = function(card)
{
//身份證號碼為15位或者18位,15位時全為數字,18位前17位為數字,最後一位是校驗位,可能為數字或字元X
var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
if(reg.test(card) === false)
{
return false;
}
return true;
};
//取身份證前兩位,校驗省份
checkProvince = function(card)
{
var province = card.substr(0,2);
if(vcity[province] == undefined)
{
return false;
}
return true;
};
//檢查生日是否正確
checkBirthday = function(card)
{
var len = card.length;
//身份證15位時,次序為省(3位)市(3位)年(2位)月(2位)日(2位)校驗位(3位),皆為數字
if(len == '15')
{
var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
var arr_data = card.match(re_fifteen);
var year = arr_data[2];
var month = arr_data[3];
var day = arr_data[4];
var birthday = new Date('19'+year+'/'+month+'/'+day);
return verifyBirthday('19'+year,month,day,birthday);
}
//身份證18位時,次序為省(3位)市(3位)年(4位)月(2位)日(2位)校驗位(4位),校驗位末尾可能為X
if(len == '18')
{
var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
var arr_data = card.match(re_eighteen);
var year = arr_data[2];
var month = arr_data[3];
var day = arr_data[4];
var birthday = new Date(year+'/'+month+'/'+day);
return verifyBirthday(year,month,day,birthday);
}
return false;
};
//校驗日期
verifyBirthday = function(year,month,day,birthday)
{
var now = new Date();
var now_year = now.getFullYear();
//年月日是否合理
if(birthday.getFullYear() == year && (birthday.getMonth() + 1) == month && birthday.getDate() == day)
{
//判斷年份的范圍(3歲到100歲之間)
var time = now_year - year;
if(time >= 3 && time <= 100)
{
return true;
}
return false;
}
return false;
};
//校驗位的檢測
checkParity = function(card)
{
//15位轉18位
card = changeFivteenToEighteen(card);
var len = card.length;
if(len == '18')
{
var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
var cardTemp = 0, i, valnum;
for(i = 0; i < 17; i ++)
{
cardTemp += card.substr(i, 1) * arrInt[i];
}
valnum = arrCh[cardTemp % 11];
if (valnum == card.substr(17, 1))
{
return true;
}
return false;
}
return false;
};
//15位轉18位身份證號
changeFivteenToEighteen = function(card)
{
if(card.length == '15')
{
var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
var cardTemp = 0, i;
card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
for(i = 0; i < 17; i ++)
{
cardTemp += card.substr(i, 1) * arrInt[i];
}
card += arrCh[cardTemp % 11];
return card;
}
return card;
};
</script>
</head>
<body>
<form name="form1" method="post" action="">
<label>身份證號
<input name='card_no' type='text' id='card_no' onBlur='javascript:checktheform();'/>
</label>
<label>
<input type="submit" name="Submit" value="提交">
</label>
</form></body>
</html>