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