以下是 AJAX验证表单特效代码 的示例演示效果:
部分效果截图1:
部分效果截图2:
HTML代码(index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta name="keywords" content="JS代码,其他代码,JS广告代码,JS特效代码" />
<meta name="description" content="此代码内容为AJAX验证表单下载,属于站长常用代码" />
<title>AJAX验证表单下载</title>
<!--
/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
*
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
-->
<head>
<script src="scriptaculous/lib/prototype.js" type="text/javascript"></script>
<script src="scriptaculous/src/effects.js" type="text/javascript"></script>
<script type="text/javascript" src="fabtabulous.js"></script>
<script type="text/javascript" src="validation.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="container">
<h1>Really Easy Field validation with Prototype</h1>
<div id="mainmenu">
<ul id="tabs">
<li>
<a href="#standard">Standard</a>
</li>
<li>
<a href="#using-titles">Using Titles</a>
</li>
<li>
<a href="#no-element-ids">No element IDs</a>
</li>
</ul>
<div>
<div class="bar"> </div>
<div class="panel" id="standard">
<form id="test" action="#" method="get">
<fieldset>
<legend>Form</legend>
<div class="form-row">
<div class="field-label"><label for="field1">Name</label>:</div>
<div class="field-widget"><input name="field1" id="field1" class="required" title="Enter your name" /></div>
</div>
<div class="form-row">
<div class="field-label"><label for="field8">Password</label>:</div>
<div class="field-widget"><input type="password" name="field8" id="field8" class="required validate-password" title="Enter a password greater than 6 characters" /></div>
</div>
<div class="form-row">
<div class="field-label"><label for="field9">Confirm Password</label>:</div>
<div class="field-widget"><input type="password" name="field9" id="field9" class="required validate-password-confirm" title="Enter the same password for confirmation" /></div>
</div>
<div class="form-row">
<div class="field-label"><label for="field3">Employee Number</label>:</div>
<div class="field-label">
<input name="field3" id="field3" class="required validate-alphanum" title="Enter your employee number, please use only alphanumeric characters" />
</div>
</div>
<div class="form-row">
<div class="field-label"><label for="field7">Department</label>:</div>
<div class="field-widget">
<select id="field7" name="field7" class="validate-selection" title="Choose your department">
<option>Select one...</option>
<option>Accounts</option>
<option>Human Resources</option>
<option>Information Technology</option>
<option>Animal Management</option>
<option>Ultimate Frisby</option>
</select>
</div>
</div>
<div class="form-row">
<div class="field-label"><label for="field4">Age</label>:</div>
<div class="field-label"><input name="field4" id="field4" class="validate-number" title="Optional: Enter your age" /> (optional)</div>
</div>
<div class="form-row">
<div class="field-label"><label for="field6">Sex</label>:</div>
<div class="field-label">
<input type="radio" name="field6" id="field6-male" value="Male" />Male<br />
<input type="radio" name="field6" id="field6-female" value="Female" class="validate-one-required" />Female
</div>
</div>
<div class="form-row">
<div class="field-label"><label for="field5">Donation</label>:</div>
<div class="field-label">
<div id="advice-validate-currency-dollar-field5" class="custom-advice" style="display:none">That $ amount does not compute!</div>
<input name="field5" id="field5" class="validate-currency-dollar" title="Enter a dollar amount for donation" /> (optional)
</div>
</div>
<p><a href="#" onclick="$('email-signup').toggle(); return false">Sign me up for the email newletter!</a></p>
<div id="email-signup" class="form-row" style="display:none;">
<div class="field-label"><label for="field22">Email</label>:</div>
<div class="field-widget"><input name="field22" id="field22" class="required validate-email" title="Optional: Enter your email address" /></div>
</div>
</fieldset>
<input type="submit" value="Submit" /> <input type="button" value="Reset" onclick="valid.reset(); return false" />
</form>
<script type="text/javascript">
function formCallback(result, form) {
window.status = "valiation callback for form '" + form.id + "': result = " + result;
}
var valid = new Validation('test', {immediate : true, onFormValidate : formCallback});
Validation.addAllThese([
['validate-password', 'Your password must be more than 6 characters and not be \'password\' or the same as your name', {
minLength : 7,
notOneOf : ['password','PASSWORD','1234567','0123456'],
notEqualToField : 'field1'
}],
['validate-password-confirm', 'Your confirmation password does not match your first password, please try again.', {
equalToField : 'field8'
}]
]);
</script>
</div>
<div class="panel" id="using-titles">
<form id="test2" action="#" method="get">
<fieldset>
<legend>Form</legend>
<div class="form-row">
<div class="field-label"><label for="field1-t2">Name</label>:</div>
<div class="field-widget"><input name="field1-t2" id="field1-t2" class="required" title="Enter your name. This is a required field" /></div>
</div>
<div class="form-row">
<div class="field-label"><label for="field3-t2">Employee Number</label>:</div>
<div class="field-label"><input name="field3-t2" id="field3-t2" class="required validate-alphanum" title="Enter your employee number, please use only alphanumeric characters" /></div>
</div>
<div class="form-row">
<div class="field-label"><label for="field4-t2">Age</label>:</div>
<div class="field-label"><input name="field4-t2" id="field4-t2" class="validate-number" title="Optional: Enter your age, please use only numbers" /> (optional)</div>
</div>
<div class="form-row">
<div class="field-label"><label for="field5-t2">Donation</label>:</div>
<div class="field-label"><input name="field5-t2" id="field5-t2" class="validate-currency-dollar" title="Optional: Enter a dollar amount for donation" /> (optional)</div>
</div>
</fieldset>
<input type="submit" value="Submit" /> <input type="button" value="Reset" onclick="valid2.reset(); return false" />
</form>
<script type="text/javascript">
var valid2 = new Validation('test2', {useTitles:true});
</script>
</div>
<div class="panel" id="no-element-ids">
<form id="test3" action="#" method="get">
<fieldset>
<legend>Form</legend>
<div class="form-row">
<div class="field-label"><label for="field1-t3">Name</label>:</div>
<div class="field-widget"><input name="field1-t3" class="required" title="Enter your name. This is a required field" /></div>
</div>
<div class="form-row">
<div class="field-label"><label for="field2-t3">Employee Number</label>:</div>
<div class="field-label"><input name="field2-t3" class="required validate-alphanum" title="Enter your employee number, please use only alphanumeric characters" /></div>
</div>
<div class="form-row">
<div class="field-label"><label for="field3-t3">Age</label>:</div>
<div class="field-label"><input name="field3-t3" class="validate-number" title="Optional: Enter your age, please use only numbers" /> (optional)</div>
</div>
<div class="form-row">
<div class="field-label"><label for="field4-t3">Donation</label>:</div>
<div class="field-label"><input name="field4-t3" class="validate-currency-dollar" title="Optional: Enter a dollar amount for donation" /> (optional)</div>
</div>
</fieldset>
<input type="submit" value="Submit" /> <input type="button" value="Reset" onclick="valid3.reset(); return false" />
</form>
<script type="text/javascript">
var valid3 = new Validation('test3');
</script>
</div>
</div>
<script type="text/javascript">
new Fabtabs('tabs');
</script>
</body>
</html>
JS代码(fabtabulous.js):
/* * Fabtabulous! Simple tabs using Prototype * http://tetlaw.id.au/view/blog/fabtabulous-simple-tabs-using-prototype/ * Andrew Tetlaw * version 1.1 2006-05-06 * http://creativecommons.org/licenses/by-sa/2.5/ */
var Fabtabs = Class.create();
Fabtabs.prototype ={
initialize:function(element){
this.element = $(element);
var options = Object.extend({
}
,arguments[1] ||{
}
);
this.menu = $A(this.element.getElementsByTagName('a'));
this.show(this.getInitialTab());
this.menu.each(this.setupTab.bind(this));
}
,setupTab:function(elm){
Event.observe(elm,'click',this.activate.bindAsEventListener(this),false)}
,activate:function(ev){
var elm = Event.findElement(ev,"a");
//Event.stop(ev);
this.show(elm);
this.menu.without(elm).each(this.hide.bind(this));
}
,hide:function(elm){
$(elm).removeClassName('active-tab');
$(this.tabID(elm)).removeClassName('active-tab-body');
}
,show:function(elm){
$(elm).addClassName('active-tab');
$(this.tabID(elm)).addClassName('active-tab-body');
}
,tabID:function(elm){
return elm.href.match(/#(\w.+)/)[1];
}
,getInitialTab:function(){
if(document.location.href.match(/#(\w.+)/)){
var loc = RegExp.$1;
var elm = this.menu.find(function(value){
return value.href.match(/#(\w.+)/)[1] == loc;
}
);
return elm || this.menu.first();
}
else{
return this.menu.first();
}
}
}
Event.observe(window,'load',function(){
new Fabtabs('tabs');
}
,false);
JS代码(validation.js):
/** Really easy field validation with Prototype* http://tetlaw.id.au/view/javascript/really-easy-field-validation* Andrew Tetlaw* Version 1.5.4.1 (2007-01-05)** Copyright (c) 2007 Andrew Tetlaw* Permission is hereby granted,free of charge,to any person* obtaining a copy of this software and associated documentation* files (the "Software"),to deal in the Software without* restriction,including without limitation the rights to use,copy,* modify,merge,publish,distribute,sublicense,and/or sell copies* of the Software,and to permit persons to whom the Software is* furnished to do so,subject to the following conditions:** The above copyright notice and this permission notice shall be* included in all copies or substantial portions of the Software.** THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,* EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF* MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS* BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHER IN AN* ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF OR IN* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE* SOFTWARE.**/
var Validator = Class.create();
Validator.prototype ={
initialize:function(className,error,test,options){
if(typeof test == 'function'){
this.options = $H(options);
this._test = test;
}
else{
this.options = $H(test);
this._test = function(){
return true}
;
}
this.error = error || 'Validation failed.';
this.className = className;
}
,test:function(v,elm){
return (this._test(v,elm) && this.options.all(function(p){
return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value):true;
}
));
}
}
Validator.methods ={
pattern:function(v,elm,opt){
return Validation.get('IsEmpty').test(v) || opt.test(v)}
,minLength:function(v,elm,opt){
return v.length >= opt}
,maxLength:function(v,elm,opt){
return v.length <= opt}
,min:function(v,elm,opt){
return v >= parseFloat(opt)}
,max:function(v,elm,opt){
return v <= parseFloat(opt)}
,notOneOf:function(v,elm,opt){
return $A(opt).all(function(value){
return v != value;
}
)}
,oneOf:function(v,elm,opt){
return $A(opt).any(function(value){
return v == value;
}
)}
,is:function(v,elm,opt){
return v == opt}
,isNot:function(v,elm,opt){
return v != opt}
,equalToField:function(v,elm,opt){
return v == $F(opt)}
,notEqualToField:function(v,elm,opt){
return v != $F(opt)}
,include:function(v,elm,opt){
return $A(opt).all(function(value){
return Validation.get(value).test(v,elm);
}
)}
}
var Validation = Class.create();
Validation.prototype ={
initialize:function(form,options){
this.options = Object.extend({
onSubmit:true,stopOnFirst:false,immediate:false,focusOnError:true,useTitles:false,onFormValidate:function(result,form){
}
,onElementValidate:function(result,elm){
}
}
,options ||{
}
);
this.form = $(form);
if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
if(this.options.immediate){
var useTitles = this.options.useTitles;
var callback = this.options.onElementValidate;
Form.getElements(this.form).each(function(input){
// Thanks Mike!Event.observe(input,'blur',function(ev){
Validation.validate(Event.element(ev),{
useTitle:useTitles,onElementValidate:callback}
);
}
);
}
);
}
}
,onSubmit:function(ev){
if(!this.validate()) Event.stop(ev);
}
,validate:function(){
var result = false;
var useTitles = this.options.useTitles;
var callback = this.options.onElementValidate;
if(this.options.stopOnFirst){
result = Form.getElements(this.form).all(function(elm){
return Validation.validate(elm,{
useTitle:useTitles,onElementValidate:callback}
);
}
);
}
else{
result = Form.getElements(this.form).collect(function(elm){
return Validation.validate(elm,{
useTitle:useTitles,onElementValidate:callback}
);
}
).all();
}
if(!result && this.options.focusOnError){
Form.getElements(this.form).findAll(function(elm){
return $(elm).hasClassName('validation-failed')}
).first().focus()}
this.options.onFormValidate(result,this.form);
return result;
}
,reset:function(){
Form.getElements(this.form).each(Validation.reset);
}
}
Object.extend(Validation,{
validate:function(elm,options){
options = Object.extend({
useTitle:false,onElementValidate:function(result,elm){
}
}
,options ||{
}
);
elm = $(elm);
var cn = elm.classNames();
return result = cn.all(function(value){
var test = Validation.test(value,elm,options.useTitle);
options.onElementValidate(test,elm);
return test;
}
);
}
,test:function(name,elm,useTitle){
var v = Validation.get(name);
var prop = '__advice'+name.camelize();
try{
if(Validation.isVisible(elm) && !v.test($F(elm),elm)){
if(!elm[prop]){
var advice = Validation.getAdvice(name,elm);
if(advice == null){
var errorMsg = useTitle ? ((elm && elm.title) ? elm.title:v.error):v.error;
advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'switch (elm.type.toLowerCase()){
case 'checkbox':case 'radio':var p = elm.parentNode;
if(p){
new Insertion.Bottom(p,advice);
}
else{
new Insertion.After(elm,advice);
}
break;
default:new Insertion.After(elm,advice);
}
advice = Validation.getAdvice(name,elm);
}
if(typeof Effect == 'undefined'){
advice.style.display = 'block';
}
else{
new Effect.Appear(advice,{
duration:1}
);
}
}
elm[prop] = true;
elm.removeClassName('validation-passed');
elm.addClassName('validation-failed');
return false;
}
else{
var advice = Validation.getAdvice(name,elm);
if(advice != null) advice.hide();
elm[prop] = '';
elm.removeClassName('validation-failed');
elm.addClassName('validation-passed');
return true;
}
}
catch(e){
throw(e)}
}
,isVisible:function(elm){
while(elm.tagName != 'BODY'){
if(!$(elm).visible()) return false;
elm = elm.parentNode;
}
return true;
}
,getAdvice:function(name,elm){
return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
}
,getElmID:function(elm){
return elm.id ? elm.id:elm.name;
}
,reset:function(elm){
elm = $(elm);
var cn = elm.classNames();
cn.each(function(value){
var prop = '__advice'+value.camelize();
if(elm[prop]){
var advice = Validation.getAdvice(value,elm);
advice.hide();
elm[prop] = '';
}
elm.removeClassName('validation-failed');
elm.removeClassName('validation-passed');
}
);
}
,add:function(className,error,test,options){
var nv ={
}
;
nv[className] = new Validator(className,error,test,options);
Object.extend(Validation.methods,nv);
}
,addAllThese:function(validators){
var nv ={
}
;
$A(validators).each(function(value){
nv[value[0]] = new Validator(value[0],value[1],value[2],(value.length > 3 ? value[3]:{
}
));
}
);
Object.extend(Validation.methods,nv);
}
,get:function(name){
return Validation.methods[name] ? Validation.methods[name]:Validation.methods['_LikeNoIDIEverSaw_'];
}
,methods:{
'_LikeNoIDIEverSaw_':new Validator('_LikeNoIDIEverSaw_','',{
}
)}
}
);
Validation.add('IsEmpty','',function(v){
return ((v == null) || (v.length == 0));
// || /^\s+$/.test(v));
}
);
Validation.addAllThese([['required','This is a required field.',function(v){
return !Validation.get('IsEmpty').test(v);
}
],['validate-number','Please enter a valid number in this field.',function(v){
return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
}
],['validate-digits','Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.',function(v){
return Validation.get('IsEmpty').test(v) || !/[^\d]/.test(v);
}
],['validate-alpha','Please use letters only (a-z) in this field.',function (v){
return Validation.get('IsEmpty').test(v) || /^[a-zA-Z]+$/.test(v)}
],['validate-alphanum','Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.',function(v){
return Validation.get('IsEmpty').test(v) || !/\W/.test(v)}
],['validate-date','Please enter a valid date.',function(v){
var test = new Date(v);
return Validation.get('IsEmpty').test(v) || !isNaN(test);
}
],['validate-email','Please enter a valid email address. For example fred@domain.com .',function (v){
return Validation.get('IsEmpty').test(v) || /\w{
1,}
[@][\w\-]{
1,}
([.]([\w\-]{
1,}
)){
1,3}
$/.test(v)}
],['validate-url','Please enter a valid URL.',function (v){
return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)}
],['validate-date-au','Please use this date format:dd/mm/yyyy. For example 17/03/2006 for the 17th of March,2006.',function(v){
if(Validation.get('IsEmpty').test(v)) return true;
var regex = /^(\d{
2}
)\/(\d{
2}
)\/(\d{
4}
)$/;
if(!regex.test(v)) return false;
var d = new Date(v.replace(regex,'$2/$1/$3'));
return ( parseInt(RegExp.$2,10) == (1+d.getMonth()) ) &&(parseInt(RegExp.$1,10) == d.getDate()) &&(parseInt(RegExp.$3,10) == d.getFullYear() );
}
],['validate-currency-dollar','Please enter a valid $ amount. For example $100.00 .',function(v){
// [$]1[##][,###]+[.##]// [$]1###+[.##]// [$]0.##// [$].##return Validation.get('IsEmpty').test(v) || /^\$?\-?([1-9]{
1}
[0-9]{
0,2}
(\,[0-9]{
3}
)*(\.[0-9]{
0,2}
)?|[1-9]{
1}
\d*(\.[0-9]{
0,2}
)?|0(\.[0-9]{
0,2}
)?|(\.[0-9]{
1,2}
)?)$/.test(v)}
],['validate-selection','Please make a selection',function(v,elm){
return elm.options ? elm.selectedIndex > 0:!Validation.get('IsEmpty').test(v);
}
],['validate-one-required','Please select one of the above options.',function (v,elm){
var p = elm.parentNode;
var options = p.getElementsByTagName('INPUT');
return $A(options).any(function(elm){
return $F(elm);
}
);
}
]]);
CSS代码(style.css):
body{color:#333;padding:0 30px;font-family:Arial,Helvetica,sans-serif;font-size:76%;}
.panel{clear:both;display:none;border:3px solid #CCC;padding:1em;}
.panel.active-tab-body{display:block;}
#tabs{list-style:none;}
#tabs li{float:left;}
#tabs a{float:left;padding:5px 8px;margin-left:6px;background-color:#F2F2F2;text-decoration:none;color:#999999;}
#tabs a.active-tab{background-color:#CCC;border-top:3px solid #999;padding-top:3px;color:#000;}
input.disabled{border:1px solid #F2F2F2;background-color:#F2F2F2;}
input.required,textarea.required{border:1px solid #00A8E6;}
input.validation-failed,textarea.validation-failed{border:1px solid #FF3300;color:#FF3300;}
input.validation-passed,textarea.validation-passed{border:1px solid #00CC00;color:#000;}
.validation-advice{margin:5px 0;padding:5px;background-color:#FF3300;color:#FFF;font-weight:bold;}
.custom-advice{margin:5px 0;padding:5px;background-color:#C8AA00;color:#FFF;font-weight:bold;}
fieldset{padding:1em;margin-bottom:0.5em;}
label{font-weight:bold;}
.form-row{clear:both;padding:0.5em;}
.field-label{}
.field-widget{}