Html5实现用户注册自动校验功能实例代码
05-24 10:49:46作者:二当家的素材网
抽时间写了一个带有自动校验功能的Html5用户注册Demo。使用到Handlebars模板技术和手机验证码校验。
以下是效果截图:
1.页面代码:usersRegister.hbs
XML/HTML Code复制内容到剪贴板
<!DOCTYPE html>
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>用户注册</title>
<!--[if lt IE 9]>
<script src="/assets/scripts/html5shiv.js"></script>
<![endif]-->
<link href="/assets/styles/jquery.idealforms.min.css" rel="stylesheet" media="screen" />
<style type="text/css">
body {
font: normal 15px/1.5 Arial, Helvetica, Free Sans, sans-serif;
color: #222;
overflow-y: scroll;
padding: 60px 0 0 0;
}
.main {
width: 560px;
height: 480px;
margin: -50px auto;
}
#my-form {
width: 560px;
height: 450px;
margin: 0 auto;
border: 1px solid #ccc;
padding: 3em;
border-radius: 3px;
box-shadow: 0 0 2px rgba(0, 0, 0, .2);
}
</style>
<script type="text/javascript" src="/assets/scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/assets/scripts/jquery.idealforms.js"></script>
</head>
<body>
<!-- style="background-image: url(static/image/bg.jpg) -->
<p class="main" >
<p style="height:5px;text-align:center;font-size:25px"> 欢迎您注册!</p>
<!-- Begin Form -->
<form id="my-form" class="myform">
<p>
<label>用户名:</label><input id="username" name="username" type="text" />
</p>
<p>
<!-- <label>密码:</label><input id="pass" name="password" type="password" /> -->
<label>密码:</label><input id="pass" name="password" type="text" />
</p>
<p>
<label>邮箱:</label><input id="email" name="email"
data-ideal="required email" type="email" />
</p>
<p>
<label>电话:</label><input id="telephone" type="text" name="phone" data-ideal="phone" />
</p>
<p>
<label>供应商V码:</label><input id="vCode" type="text" name="vCode" data-ideal="vCode" />
</p>
<p>
<label>真实姓名:</label><input id="trueName" type="text" name="trueName" data-ideal="trueName" />
</p>
<p>
<label>手机验证码:</label><input id="telCode" type="text" name="telCode" data-ideal="telCode" />
</p>
<p style="margin-bottom:5px;">
<button id="getTelCode" type="button" style="margin-left:160px; margin-right:auto;" >获取手机校验码</button>
<hr style="margin-top:5px; margin-bottom:5px;" />
</p>
<!--<p>
<label>性别:</label>
<select id="sex" name="sex">
<option value="男">男</option>
<option value="女">女</option>
</select>
</p>
<p>
<label>昵称:</label><input id="nickName" type="text" name="nickName" data-ideal="nickName" />
</p>
<p>
nbsp; <label>年龄:</label><input id="age" type="text" name="age" data-ideal="age" />
</p>-->
<!-- <p>
<label>地址:</label><input type="text" name="address" data-ideal="address" />
</p>
<p>
<label>QQ:</label><input type="text" name="qq" data-ideal="qq" />
</p>
<p>
<label>邮编:</label><input type="text" name="zip" data-ideal="zip" />
</p>
<p>
<label>传真:</label><input type="text" name="fax" data-ideal="fax" />
</p>
<p>
<label>身份证:</label><input type="text" name="creditID" data-ideal="creditID" />
</p>
<p>
<label>出生日期:</label><input name="date" class="datepicker"
data-ideal="date" type="text" placeholder="月/日/年" />
</p>
<p>
<label>上传头像:</label><input id="file" name="file" multiple
type="file" />
</p>
<p>
<label>个人主页:</label><input name="website" data-ideal="url"
type="text" />
</p>
<p>
<label>备注:</label>
<textarea id="comments" name="comments"></textarea>
</p>
-->
<!-- <p id="languages">
<label>语言:</label> <label><input type="checkbox"
name="langs[]" value="English" />英文</label> <label><input
type="checkbox" name="langs[]" value="Chinese" />中文</label> <label><input
type="checkbox" name="langs[]" value="Spanish" />西班牙文</label> <label><input
type="checkbox" name="langs[]" value="French" />法文</label>
</p>
<p>
<label>精通几门:</label> <label><input type="radio"
name="radio" checked />1</label> <label><input type="radio"
name="radio" />2</label> <label><input type="radio" name="radio" />3</label>
<label><input type="radio" name="radio" />4</label>
</p>
<p>
<label>国籍:</label> <select id="states" name="states">
<option value="default">– 选择国籍 –</option>
<option value="AL">阿拉伯</option>
<option value="AK">中国</option>
<option value="AZ">美国</option>
<option value="AR">法国</option>
<option value="CA">英国</option>
<option value="CO">德国</option>
<option value="CT">西班牙</option>
<option value="DE">俄罗斯</option>
</select>
</p> -->
<p style="margin-top:10px; margin-left:100px;margin-right:100px;">
<button type="button" id="submit" class="submit">提交</button>
<button id="reset" type="button" >重置</button>
</p>
</form>
<!-- End Form -->
</p>
<script type="text/javascript">
var options = {
onFail : function() {
alert($myform.getInvalid().length + ' invalid fields.')
},
inputs : {
'password' : {
filters : 'required pass'
},
'username' : {
filters : 'required username'
},
'email' : {
filters : 'required email'
},
'phone' : {
filters : 'required phone'
},
'trueName' : {
filters : 'required'
},
'vCode' : {
filters : 'required'
},
'telCode' : {
filters : 'required'
}
/*
'age' : {
filters : 'required digits',
data : {
min : 16,
max : 70
}
},
'file' : {
filters : 'extension',
data : {
extension : [ 'jpg' ]
}
},
'comments' : {
filters : 'min max',
data : {
min : 50,
max : 200
}
},
'states' : {
filters : 'exclude',
data : {
exclude : [ 'default' ]
},
errors : {
exclude : '选择国籍.'
}
},
'langs[]' : {
filters : 'min max',
data : {
min : 2,
max : 3
},
errors : {
min : 'Check at least <strong>2</strong> options.',
max : 'No more than <strong>3</strong> options allowed.'
}
}
*/
}
};
$('#getTelCode').click(function() {
var telephone = document.getElementById("telephone").value; //手机号码
if (telephone == null || telephone == ""){
alert("手机号码不能为空!");
}
else{
$.ajax({
type : "GET",
dataType : "json",
url : "../api/getTelCode?telephone="+ telephone,
success : function(msg) {
},
error : function(e) {
alert("获取手机校验码失败!" + e);
}
});
}
});
var $myform = $('#my-form').idealforms(options).data('idealforms');
$('#submit').click(function() {
var username = document.getElementById("username").value; //用户名
var password = document.getElementById("pass").value; //密码
var email = document.getElementById("email").value; //邮箱
var telephone = document.getElementById("telephone").value; //手机号码
var vCode = document.getElementById("vCode").value; //公司V码
var telCode = document.getElementById("telCode").value; //手机校验码
var trueName = document.getElementById("trueName").value; //真实姓名
$.ajax({
type : "GET",
url : "../api/usersRegister?username="+ username +"password="+ password +"email="+ email +"telephone="+ telephone +"vCode="+ vCode +"telCode="+ telCode +"trueName="+ trueName,
success : function(msg) {
//获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
var curWwwPath = window.document.location.href;
//获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8083
var localhostPaht = curWwwPath.substring(0, pos);
//获取带"/"的项目名,如:/uimcardprj
var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
window.location.href = projectName + "/login";
alert("注册成功!");
},
error : function(e) {
alert("注册失败!" + e);
}
});
});
$('#reset').click(function() {
$myform.reset().fresh().focusFirst();
});
</script>
</body>
</html>
2.jq输入校验:jquery.idealforms.js
该js校验初始版本来自Cedric Ruiz,我略有修改。
部分校验的规则如下:
required: '此处是必填的.'
number: '必须是数字.',
digits: '必须是唯一的数字.'
name: '必须至少有3个字符长,并且只能包含字母.'
username: '用户名最短5位,最长30位,请使用英文字母、数字、中文和下划线. 用户名首字符必须为字母、数字、中文,不能为全数字.中文最长21个字.'
pass: '密码的位数必须的在6-15位之间,并且至少包含一个数字,一个大写字母和一个小写字母.'
strongpass: '必须至少为8个字符长,至少包含一个大写字母和一个小写字母和一个数字或特殊字符.'
email: '必须是一个有效的email地址. <em>(例: '">user@gmail.com)</em>'
phone: '必须是一个有效的手机号码. <em>(例: 18723101212)</em>'
以下是整个代码文件:
XML/HTML Code复制内容到剪贴板
/*--------------------------------------------------------------------------
jq-idealforms 2.1
* Author: Cedric Ruiz
* License: GPL or MIT
* Demo: http://elclanrs.github.com/jq-idealforms/
*
--------------------------------------------------------------------------*/
;(function ( $, window, document, undefined ) {
'use strict';
// Global Ideal Forms namespace
$.idealforms = {}
$.idealforms.filters = {}
$.idealforms.errors = {}
$.idealforms.flags = {}
$.idealforms.ajaxRequests = {}
/*--------------------------------------------------------------------------*/
/**
* @namespace A chest for various Utils
*/
var Utils = {
/**
* Get width of widest element in the collection.
* @memberOf Utils
* @param {jQuery object} $elms
* @returns {number}
*/
getMaxWidth: function( $elms ) {
var maxWidth = 0
$elms.each(function() {
var width = $(this).outerWidth()
if ( width > maxWidth ) {
maxWidth = width
}
})
return maxWidth
},
/**
* Hacky way of getting LESS variables
* @memberOf Utils
* @param {string} name The name of the LESS class.
* @param {string} prop The css property where the data is stored.
* @returns {number, string}
*/
getLessVar: function( name, prop ) {
var value = $('<p class="' + name + '"></p>').hide().appendTo('body').css( prop )
$('.' + name).remove()
return ( /^d+/.test( value ) ? parseInt( value, 10 ) : value )
},
/**
* Like ES5 Object.keys
*/
getKeys: function( obj ) {
var keys = []
for(var key in obj) {
if ( obj.hasOwnProperty( key ) ) {
keys.push( key )
}
}
return keys
},
// Get lenght of an object
getObjSize: function( obj ) {
var size = 0, key;
for ( key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
size++;
}
}
return size;
},
isFunction: function( obj ) {
return typeof obj === nbsp;'function'
},
isRegex: function( obj ) {
return obj instanceof RegExp
},
isString: function( obj ) {
return typeof obj === 'string'
},
getByNameOrId: function( str ) {
var $el = $('[name="'+ str +'"]').length
? $('[name="'+ str +'"]') // by name
: $('#'+ str) // by id
return $el.length
? $el
: $.error('The field "'+ str + '" doesn't exist.')
},
getFieldsFromArray: function( fields ) {
var f = []
for ( var i = 0, l = fields.length; i < l; i++ ) {
f.push( Utils.getByNameOrId( fields[i] ).get(0) )
}
return $( f )
},
convertToArray: function( obj ) {
return Object.prototype.toString.call( obj ) === '[object Array]'
? obj : [ obj ]
},
/**
* Determine type of any Ideal Forms element
* @param $input jQuery $input object
*/
getIdealType: function( $el ) {
var type = $el.attr('type') || $el[0].tagName.toLowerCase()
return (
/(text|password|email|number|search|url|tel|textarea)/.test( type ) && 'text' ||
/file/.test( type ) && 'file' ||
/select/.test( type ) && 'select' ||
/(radio|checkbox)/.test( type ) && 'radiocheck' ||
/(button|submit|reset)/.test( type ) && 'button' ||
/hd/.test( type ) && 'heading' ||
/hr/.test( type ) && 'separator' ||
/hidden/.test( type ) && 'hidden'
)
},
/**
* Generates an input
* @param name `name` attribute of the input
* @param type `type` or `tagName` of the input
*/
makeInput: function( name, value, type, list, placeholder ) {
var markup, items = [], item, i, len
function splitValue( str ) {
var item, value, arr
if ( /::/.test( str ) ) {
arr = str.split('::')
item = arr[ 0 ]
value = arr[ 1 ]
} else {
item = value = str
}
return { item: item, value: value }
}
// Text & file
if ( /^(text|password|email|number|search|url|tel|file|hidden)$/.test(type) )
markup = '<input '+
'type="'+ type +'" '+
'id="'+ name +'" '+
'name="'+ name +'" '+
'value="'+ value +'" '+
(placeholder && 'placeholder="'+ placeholder +'"') +
'/>'
// Textarea
if ( /textarea/.test( type ) ) {
markup = '<textarea id="'+ name +'" name="'+ name +'" value="'+ value +'"></textarea>'
}
// Select
if ( /select/.test( type ) ) {
items = []
for ( i = 0, len = list.length; i < len; i++ ) {
item = splitValue( list[ i ] ).item
value = splitValue( list[ i ] ).value
items.push('<option value="'+ value +'">'+ item +'</option>')
}
markup =
'<select id="'+ name +'" name="'+ name +'">'+
items.join('') +
'</select>'
}
// Radiocheck
if ( /(radio|checkbox)/.test( type ) ) {
items = []
for ( i = 0, len = list.length; i < len; i++ ) {
item = splitValue( list[ i ] ).item
value = splitValue( list[ i ] ).value
items.push(
'<label>'+
'<input type="'+ type +'" name="'+ name +'" value="'+ value +'" />'+
item +
'</label>'
)
}
markup = items.join('')
}
return markup
}
}
/**
* Custom tabs for Ideal Forms
*/
$.fn.idealTabs = function (container) {
var
// Elements
$contents = this,
$containercontainer = container,
$wrapper = $('<ul class="ideal-tabs-wrap"/>'),
$tabs = (function () {
var tabs = []
$contents.each(function () {
var name = $(this).attr('name')
var html =
'<li class="ideal-tabs-tab">'+
'<span>' + name + '</span>'+
'<i class="ideal-tabs-tab-counter ideal-tabs-tab-counter-zero">0</i>'+
'</li>'
tabs.push(html)
})
return $(tabs.join(''))
}()),
Actions = {
getCurIdx: function () {
return $tabs
.filter('.ideal-tabs-tab-active')
.index()
},
getTabIdxByName: function (name) {
var re = new RegExp(name, 'i')
var $tab = $tabs.filter(function () {
return re.test($(this).text())
})
return $tab.index()
}
},
/**
* Public methods
*/
Methods = {
/**
* Switch tab
*/
switchTab: function (nameOrIdx) {
var idx = Utils.isString(nameOrIdx)
? Actions.getTabIdxByName(nameOrIdx)
: nameOrIdx
$tabs.removeClass('ideal-tabs-tab-active')
$tabs.eq(idx).addClass('ideal-tabs-tab-active')
$contents.hide().eq(idx).show()
},
友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群