Home > Article > Web Front-end > js form validation method (practical)_form effects
//The following verification is the length
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
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 The maximum is "length" bits," "Please re-enter! Note: One Chinese character occupies 2 digits");
textObj.focus();
return false;
}else {
return true;
}
}
//The following verification does not contain illegal characters. Chinese, English, and numbers are all legal.
function isValidString(textId,errMsg){
szStr = document.getElementById(textId).value;
voidChar = "'">for(i = 0 ; i aChar = voidChar.substring(i, i 1);
if(szStr.indexOf( aChar) > -1){
alert(errMsg);
return false;
}
}
return true;
}
//Only letters can be entered for verification below , numbers, underlines
function isEnglish(textId,errMsg)
{
s = document.getElementById(textId).value;
//The following regular expression limits the length to between 6 and 20
//var patrn=/^(w){6,20}$/;
var patrn =/^(w)*$/;
if (!patrn.exec(s)) {
alert(errMsg);
return false
}
return true
}
//The following verification only allows Chinese
function isChinese(textId,errMsg)
{
s = document.getElementById(textId).value;
var patrn =/[^u4E00-u9FA5]/g;
if (patrn.exec(s)){
alert(errMsg );
return false
}
return true
}
//The following verification only allows numbers
function isNumber(textId,errMsg)
{
s = document .getElementById(textId).value;
//The following regular expression limits the length between 6 and 20
//var patrn=/^(d){6,20}$/;
var patrn =/^(d)*$/;
if (!patrn.exec(s)){
alert(errMsg);
return false
}
return true
}
Use js regular expressions to control not allowing non-numbers to be entered in the text box, that is, only numbers are allowed to be entered. Calling method: onkeyup="onlyNum(this);"
function onlyNum( obj)
{
temp = obj.value;
//Note that the following regular expression is written without quotation marks. .
obj.value = temp.replace(/D/g,'');
}