Posted on 2007-11-18 00:12
yukui 閱讀(782)
評論(0) 編輯 收藏 所屬分類:
技術
<script language="JavaScript">
//設置焦點函數
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
elem.focus( );
elem.select( );
}
// 驗證下拉框
function isChosen(select){
if (select.selectedIndex==0) {
alert("請選擇下拉單相應欄目.");
focusElement(select.form.name,select.name);
return false;
} else {
return true;
}
}
//不為空函數
function isNotEmpty(elem) {
var str=elem.value;
if(str==null || str.length==0) {
alert("此項不能為空");
focusElement(elem.form.name,elem.name);
return false;
} else {
return true;
}
}
// 驗證是否是數字
function isNumber(elem) {
var str=elem.value;
var oneDecimal=false;
var oneChar=0;
str=str.toString( );
for (var i=0; i<str.length; i++) {
oneChar=str.charAt(i).charCodeAt(0);
// -
if (oneChar==45) {
if (i==0) {
continue;
} else {
alert("Only the first character may be a minus sign.");
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
}
}
// 小數點
if (oneChar==46) {
if (!oneDecimal) {
oneDecimal=true;
continue;
} else {
alert("輸入的數字只允許有一個小數點.");
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
}
}
// 數字只能在0和9之間
if (oneChar<48 || oneChar > 57) {
alert("此項只能輸入數字.");
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
}
}
return true;
}
// 驗證是否是數字電話
function istel(elem) {
var str=elem.value;
var oneDecimal=false;
var oneChar=0;
str=str.toString( );
for (var i=0; i<str.length; i++) {
oneChar=str.charAt(i).charCodeAt(0);
if(oneChar==45){continue;}
if(oneChar<48 || oneChar > 57) {
alert("此項只能輸入數字和'-'號.");
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
}
}
return true;
}
//驗證輸入數據的長度
//郵編
function isLenMatch(elem,lengthNum) {
var str=elem.value;
if (str.length != lengthNum) {
alert("此項內容長度只能為"+lengthNum+"位.");
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
} else {
return true;
}
}
//郵件地址驗證
function isEMailAddr(elem) {
var str = elem.value;
var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!str.match(re)) {
alert("您輸入的不是有效的e-mail地址.");
setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
return false;
} else {
return true;
}
}
//單選按鈕驗證
function isValidRadio(radio) {
var valid=false;
for (var i=0; i<radio.length; i++) {
if (radio.checked) {
return true;
}
}
alert("單選按鈕未選中.");
radio[0].focus();
//setTimeout("focusElement('" + radio[0].form.name + "', '" + radio[0].name + "')", 0);
focusElement(radio[0].form.name,radio[0].name);
return false;
}
</script>
<script language="JavaScript">
function validateForm(form) {
if (isNotEmpty(form.name1) && isNotEmpty(form.name2)) {;}else{return false;
}
</script>
<title>JS驗證程序Sample</title></head>
<body>
<form method="GET" action="index.htm" name="sampleForm" onsubmit="return validateForm(this)">
<p>姓名:
<input type="text" size="30" name="name1" id="name1" />
</body>
</html>
表單驗證 很有用
長度限制
<script>
function test()
{
if(document.a.b.value.length>50)
{
alert("不能超過50個字符!");
document.a.b.focus();
return false;
}
}
</script>
<form name=a onsubmit="return test()">
<textarea name="b" cols="40" wrap="VIRTUAL" rows="6"></textarea>
<input type="submit" name="Submit" value="check">
</form>
2 只能是漢字
<input onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')">
3 只能是英文
<script language=javascript>
function onlyEng()
{
if(!(event.keyCode>=65&&event.keyCode<=90))
event.returnvalue=false;
}
</script>
<input onkeydown="onlyEng();">
4 只能是數字
<script language=javascript>
function onlyNum()
{
if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
//考慮小鍵盤上的數字鍵
event.returnvalue=false;
}
</script>
<input onkeydown="onlyNum();">
5 只能是英文字符和數字
<input onkeyup="value=value.replace(/[\W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
6 驗證油箱格式
<SCRIPT LANGUAGE=javascript RUNAT=Server>
function isEmail(strEmail) {
if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
return true;
else
alert("oh");
}
</SCRIPT>
<input type=text onblur=isEmail(this.value)>
7 屏蔽關鍵字(這里屏蔽sex和****)
<script language="javascript1.2">
function test() {
if((a.b.value.indexOf ("sex") == 0)||(a.b.value.indexOf ("****") == 0)){
alert("");
a.b.focus();
return false;}
}
</script>
<form name=a onsubmit="return test()">
<input type=text name=b>
<input type="submit" name="Submit" value="check">
</form>
8 兩次輸入密碼是否相同
<FORM METHOD=POST ACTION="">
<input type="password" id="input1">
<input type="password" id="input2">
<input type="button" value="test" onclick="check()">
</FORM>
<script>
function check()
{
with(document.all){
if(input1.value!=input2.value)
{
alert("false")
input1.value = "";
input2.value = "";
}
else document.forms[0].submit();
}
}
</script>
網頁表單的javascript集成驗證方法舉例
原理:
表單驗證無非是要對要收集每一條信息進行驗證,也就是要寫一個名為
frmValid的javascript函數,在其中執行如下操作:
...
if (待驗證條目 不符合條件)
{
alert('出錯了!');
待驗證條目.focus();
return false;
}
...
// all right
return true;
當然,<form ... onsubmit='return frmValid()'>必須包含在
HTML代碼中。想想看,待驗證條目越多代碼越長,也就越容易出錯。
下面我們把驗證條目放到一個數組里,如下:
elemArray = new Array(
'待驗證條目名',
'驗證條件',
'出錯提示');
那么驗證代碼將大大精簡,我們只要如下使用循環就可實現上述冗長
代碼時下的功能,這里我們用with和eval語句構造判斷條件:
with(eval('obj.'+elems[0]))
{
if(eval(elems[1]))
{
window.alert(elems[2]);
focus();
return false;
}
}
我們建立多位數組就可實現循環遍歷每個條目:
elems = new Array(
new Arrary( ...),
...
);
for(i = 0; i < elems.length; i++)
{
// 上面的驗證語句
}
實戰:
1、使用如下例子編寫驗證腳本:
<SCRIPT LANGUAGE="javascript" type="text/javascript">
//
// Function: frmValid
// ------------------
// Author hongz
// Usage: YourForm.onsbumit="return frmValid(this)".
// Purpose: To validate form elements in an integrated way.
//
function frmValid(obj)
{
// Elements array, initialization for validation
elems = new Array(
new Array(
'username', // name of elements to be validated
'value.length<1 || value.search(/[^a-zA-z0-9_]/)>=0',
// validation condition
'無效的用戶名:只能輸入6-20位字母、數字、下劃線的組合!'),
// prompt on failure
new Array(
'password',
'value.length<5 || value.search(/[^a-zA-z0-9_]/)>=0',
'無效的密碼:只能輸入6-20位字母、數字、下劃線的組合!'),
new Array(
'email',
'isMail(value)==false',
'Email是您在網上的重要聯絡工具,請務必正確填寫!')
);
// Validate here, using eval statement.
for(i = 0; i < elems.length; i++)
{
with(eval('obj.'+elems[0]))
{
if(eval(elems[1]))
{
window.alert(elems[2]);
focus();
return false;
}
}
}
return true;
}
//-->
</SCRIPT>
2、為form添加onsubmit屬性:
<form ... onsubmit='return frmValid(this)'>
Javascript客戶端驗證代碼
代碼:
--------------------------------------------------------------------------------
<SCRIPT language=JavaScript><!--
function passwordt(theForm){
if (theForm.user_name.value == ""){
alert("登錄用戶名不能為空,請重新填寫!");
theForm.user_name.focus();
return (false);
}
if (theForm.user_pass.value == ""){
alert("登錄密碼不能為空,請重新填寫!");
theForm.user_pass.focus();
return (false);
}
if (theForm.user_pass.value.length < 3){
alert("登錄密碼不能少于3個字符,請重新填寫!");
theForm.user_pass.focus();
return (false);
}
if (theForm.re_password.value == ""){
alert("確認新密碼不能為空,請重新填寫!");
theForm.re_password.focus();
return (false);
}
if (theForm.re_password.value.length < 3){
alert("確認新密碼不能少于3個字符,請重新填寫!");
theForm.re_password.focus();
return (false);
}
if (theForm.user_pass.value != theForm.re_password.value){
alert("新密碼和確認新密碼不同,請重新填寫!");
theForm.user_pass.focus();
return (false);
}
if (theForm.user_namec.value=="") {
alert ('請填寫姓名!');
theForm.user_namec.focus();
return false;
}
if ((!theForm.user_sex(0).checked)&&(!theForm.user_sex(1).checked)){
alert ('請選擇用戶性別!');
theForm.user_sex(0).focus();
return false;
}
if ((theForm.user_birth_year.value == "")||(fucCheckNUM(theForm.user_birth_year.value)==0)||(theForm.user_birth_year.value.length!=4)||((theForm.user_birth_year.value <1900) || (theForm.user_birth_year.value >2002 ) )) {
alert("請填寫正確的出生年份!");
theForm.user_birth_year.focus();
return (false);
}
if (theForm.user_birth_month.value=="0"){
alert("請選擇出生月份!");
theForm.user_birth_month.focus();
return (false);
}
if (theForm.user_birth_day.value=="0"){
alert("請選擇出生日期!");
theForm.user_birth_day.focus();
return (false);
}
if ((theForm.user_birth_month.value=="2") && (theForm.user_birth_day.value>29)){
alert("請選擇正確的出生日期!");
theForm.user_birth_month.focus();
return (false);
}
if (((theForm.user_birth_month.value=="4")||(theForm.user_birth_month.value=="6")||(theForm.user_birth_month.value=="9")||(theForm.user_birth_month.value=="11")) && (theForm.user_birth_day.value==31)){
alert("請選擇正確的出生日期!");
theForm.user_birth_month.focus();
return (false);
}
if (theForm.user_country.value=="") {
alert("請選擇所在國家!");
theForm.user_country.focus();
return (false);
}
if (theForm.user_city.value =="") {
alert("請選擇城市!");
theForm.user_city.focus();
return (false);
}
if (theForm.user_adds.value == "" ){
alert("家庭住址不能為空,請重新填寫!");
theForm.user_adds.focus();
return (false);
}
if (theForm.user_postcode.value == "" ) {
alert("郵政編碼不能為空,請重新填寫!");
theForm.user_postcode.focus();
return (false);
}
if (theForm.user_tel.value == "" ) {
alert("郵政編碼不能為空,請重新填寫!");
theForm.user_tel.focus();
return (false);
}
if (theForm.user_mail.value=="") {
alert("請填寫EMAIL!");
theForm.user_mail.focus();
return (false);
}
if ((theForm.user_mail.value!="") && (chkemail(theForm.user_mail.value)==0)) {
alert("EMAIL格式不對,請重新填寫!");
theForm.user_mail.focus();
return (false);
}
return (true);
}
function chkemail(a){
var i=a.length;
var temp = a.indexOf('@');
var tempd = a.indexOf('.');
if (temp > 1) {
if ((i-temp) > 3){
if ((i-tempd)>0){
return 1;
}
}
}
return 0;
}
function fucCheckNUM(NUM) {
var i,j,strTemp;
strTemp="0123456789";
if ( NUM.length== 0)
return 0
for (i=0;i<NUM.length;i++) {
j=strTemp.indexOf(NUM.charAt(i));
if (j==-1) {
return 0;
}
}
return 1;
}
function chg_nation(nation){
if (nation!='cn'){
ini_province(nation);
document.user_form.selProvince.disabled = true;
document.user_form.selProvince.value="國外城市";
document.user_form.selCity.value="國外城市";
}else{
ini_province(nation);
document.user_form.selProvince.disabled = false;
document.user_form.selProvince.value="0";
document.user_form.selCity.value="";
}
}
function chg_province(province){
obj=document.getElementById("list_city");
obj.src="list_city.php?province="+province;
}
//-->
</SCRIPT>