最實用的js表單驗證方法

來源:互聯網
上載者:User

        每次都要用到表單驗證的時候,就在到處找東西,而網上的很多都不見的好用。自己終於累計了這些方法,在自己的程式中使用了的一些方法,肯定是好用的,主要使用了簡單的Regex進行判斷。如果有bug,歡迎提出來。

//下面驗證的是長度
function checkTextLen(textId){

var len = 0;
var checkField=document.getElementById(textId);
var inputstring = checkField.value;
var string_length = inputstring.length;
if (string_length == 0)
{
return 0;
}
for (var i=0;i<string_length;i++)
{
if (inputstring.charAt(i).charCodeAt()>255) len+=2;
else len+=1;
}
return len;

}

function checkTextLength(textId,length,msg){
var textObj =document.getElementById(textId);
if(checkTextLen(textId)>length/1){
alert("["+msg+"]"+"長度最大為"+length+"位,"+"請重新輸入!注意:一個漢字佔2位");
textObj.focus();
return false;
}else {
return true;
}
}

//下面驗證不含有非法的字元,中文,英文,數字都是合法的。

function isValidString(textId,errMsg){szStr = document.getElementById(textId).value;voidChar = "'\"><`~!@#$%^&\(\)()!¥……??“”‘’*";for(i = 0 ; i < voidChar.length; i ++){aChar = voidChar.substring(i, i + 1);if(szStr.indexOf(aChar) > -1){alert(errMsg);return false;}}return true;}

//下面驗證只可以輸入字母,數字,底線

function isEnglish(textId,errMsg)

{

s = document.getElementById(textId).value;

//下面的Regex限制的長度在6到20之間

//var patrn=/^(\w){6,20}$/;

var patrn =/^(\w)*$/;

if (!patrn.exec(s)){

alert(errMsg);

return false

}

return true

}

//下面驗證只允許中文

function isChinese(textId,errMsg)

{

s = document.getElementById(textId).value;

var patrn =/[^\u4E00-\u9FA5]/g;

if (patrn.exec(s)){

alert(errMsg);

return false

}

return true

}

//下面驗證只允許數字

function isNumber(textId,errMsg)

{

s = document.getElementById(textId).value;

//下面的Regex限制的長度在6到20之間

//var patrn=/^(\d){6,20}$/;

var patrn =/^(\d)*$/;

if (!patrn.exec(s)){

alert(errMsg);

return false

}

return true

}

使用js的Regex用來控制不允許在文字框裡面輸入非數字,也就是只允許輸入數字。調用方法 : onkeyup="onlyNum(this);"

function onlyNum(obj)

{

temp = obj.value;

//注意下面的Regex的寫法,沒有用引號括起來。。

obj.value = temp.replace(/\D/g,'');

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.