当前位置: 代码迷 >> JavaScript >> 简略JS自定义验证提示效果
  详细解决方案

简略JS自定义验证提示效果

热度:158   发布时间:2012-10-24 14:15:58.0
简单JS自定义验证提示效果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
<title>FormValid Demo3 自定义错误信息显示方式2</title>  
<script language="JavaScript" type="text/javascript">  
var FormValid = function(frm) {  
    this.frm = frm;  
    this.errMsg = new Array();  
    this.errName = new Array();  
     
    this.required = function(inputObj) {  
        if (typeof(inputObj) == "undefined" || inputObj.value.trim() == "") {  
            return false;  
        }  
        return true;  
    }  
      
    this.eqaul = function(inputObj, formElements) {  
        var fstObj = inputObj;  
        var sndObj = formElements[inputObj.getAttribute('eqaulName')];  
          
        if (fstObj != null && sndObj != null) {  
            if (fstObj.value != sndObj.value) {  
               return false;  
            }  
        }  
        return true;  
    }  
 
    this.gt = function(inputObj, formElements) {  
        var fstObj = inputObj;  
        var sndObj = formElements[inputObj.getAttribute('eqaulName')];  
          
        if (fstObj != null && sndObj != null && fstObj.value.trim()!='' && sndObj.value.trim()!='')   
 
{  
            if (fstObj.value <= sndObj.value) {  
                 return false;  
            }  
        }  
        return true;  
    }  
 
    this.compare = function(inputObj, formElements) {  
        var fstObj = inputObj;  
        var sndObj = formElements[inputObj.getAttribute('objectName')];  
        if (fstObj != null && sndObj != null && fstObj.value.trim()!='' && sndObj.value.trim()!='')   
 
{  
            if (!eval('fstObj.value' + inputObj.getAttribute('operate') + 'sndObj.value')) {  
                 return false;  
            }  
        }  
        return true;  
    }  
      
    this.limit = function (inputObj) {  
        var len = inputObj.value.length;  
        if (len) {  
            var minv = inputObj.getAttribute('min');  
            var maxv = inputObj.getAttribute('max');  
            minv = minv || 0;  
            maxv = maxv || Number.MAX_VALUE;  
            return minv <= len && len <= maxv;  
        }  
        return true;  
    }  
      
    this.range = function (inputObj) {  
        var val = parseInt(inputObj.value);  
        if (inputObj.value) {  
            var minv = inputObj.getAttribute('min');  
            var maxv = inputObj.getAttribute('max');  
            minv = minv || 0;  
            maxv = maxv || Number.MAX_VALUE;  
          
            return minv <= val && val <= maxv;  
        }  
        return true;  
    }  
      
    this.requireChecked = function (inputObj) {  
        var minv = inputObj.getAttribute('min');  
        var maxv = inputObj.getAttribute('max');  
        minv = minv || 1;  
        maxv = maxv || Number.MAX_VALUE;  
      
        var checked = 0;  
        var groups = document.getElementsByName(inputObj.name);  
          
        for(var i=0;i<groups.length;i++) {  
            if(groups[i].checked) checked++;  
              
        }  
        return minv <= checked && checked <= maxv;  
    }  
      
    this.filter = function (inputObj) {  
        var value = inputObj.value;  
        var allow = inputObj.getAttribute('allow');  
        if (value.trim()) {  
            return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g,   
 
allow.split(/\s*,\s*/).join("|")), "gi").test(value);  
        }  
        return true;  
    }  
      
    this.isNo = function (inputObj) {  
        var value = inputObj.value;  
        var noValue = inputObj.getAttribute('noValue');  
        return value!=noValue;  
    }  
    this.checkReg = function(inputObj, reg, msg) {  
        inputObj.value = inputObj.value.trim();  
 
        if (inputObj.value == '') {  
            return;  
        } else {  
            if (!reg.test(inputObj.value)) {  
                this.addErrorMsg(inputObj.name,msg);  
            }  
        }  
    }  
 
    this.passed = function() {  
        if (this.errMsg.length > 0) {  
            FormValid.showError(this.errMsg,this.errName);  
            frt = document.getElementsByName(this.errName[0])[0];  
              
            if (frt.type!='radio' && frt.type!='checkbox') {  
                frt.focus();  
            }  
            return false;  
        } else {  
          return true;  
        }  
    }  
 
    this.addErrorMsg = function(name,str) {  
        this.errMsg.push(str);  
        this.errName.push(name);  
    }  
      
    this.addAllName = function(name) {  
        FormValid.allName.push(name);  
    }  
      
}  
FormValid.allName = new Array();  
FormValid.showError = function(errMsg) {  
    var msg = "";  
    for (i = 0; i < errMsg.length; i++) {  
        msg += "- " + errMsg[i] + "\n";  
    }  
 
    alert(msg);  
}  
function validator(frm) {  
    var formElements = frm.elements;  
    var fv = new FormValid(frm);  
      
    for (var i=0; i<formElements.length;i++) {  
        var validType = formElements[i].getAttribute('valid');  
        var errorMsg = formElements[i].getAttribute('errmsg');  
        if (validType==null) continue;  
        fv.addAllName(formElements[i].name);  
 
        var vts = validType.split('|');  
        var ems = errorMsg.split('|');  
        for (var j=0; j<vts.length; j++) {  
            var curValidType = vts[j];  
            var curErrorMsg = ems[j];  
              
            switch (curValidType) {  
            case 'isNumber':  
            case 'isEmail':  
            case 'isPhone':  
            case 'isMobile':  
            case 'isIdCard':  
            case 'isMoney':  
            case 'isZip':  
            case 'isQQ':  
            case 'isInt':  
            case 'isEnglish':  
            case 'isChinese':  
            case 'isUrl':  
            case 'isDate':  
            case 'isTime':  
                fv.checkReg(formElements[i],RegExps  
 
[curValidType],curErrorMsg);  
                break;  
            case 'regexp':  
                fv.checkReg(formElements[i],new RegExp  
 
(formElements[i].getAttribute('regexp'),"g"),curErrorMsg);  
                break;  
            case 'custom':  
                if (!eval(formElements[i].getAttribute('custom')  
 
+'(formElements[i],formElements)')) {  
                    fv.addErrorMsg(formElements  
 
[i].name,curErrorMsg);  
                }  
                break;  
            default :  
                if (!eval('fv.'+curValidType+'(formElements  
 
[i],formElements)')) {  
                    fv.addErrorMsg(formElements  
 
[i].name,curErrorMsg);  
                }  
                break;  
            }  
        }  
    }  
    return fv.passed();  
}  
String.prototype.trim = function() {  
    return this.replace(/^\s*|\s*$/g, "");  
}  
var RegExps = function(){};  
RegExps.isNumber = /^[-\+]?\d+(\.\d+)?$/;  
RegExps.isEmail = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]  
 
{2,4}|[0-9]{1,3})(\]?)/;  
RegExps.isPhone = /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d  
 
{1,4})?$/;  
RegExps.isMobile = /^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/;  
RegExps.isIdCard = /(^\d{15}$)|(^\d{17}[0-9Xx]$)/;  
RegExps.isMoney = /^\d+(\.\d+)?$/;  
RegExps.isZip = /^[1-9]\d{5}$/;  
RegExps.isQQ = /^[1-9]\d{4,10}$/;  
RegExps.isInt = /^[-\+]?\d+$/;  
RegExps.isEnglish = /^[A-Za-z]+$/;  
RegExps.isChinese =  /^[\u0391-\uFFE5]+$/;  
RegExps.isUrl = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;  
RegExps.isDate = /^\d{4}-\d{1,2}-\d{1,2}$/;  
RegExps.isTime = /^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}$/;  
</script>  
<script type="text/javascript">  
FormValid.showError = function(errMsg) {  
    var msg = '';  
    for (key in errMsg) {  
        msg += errMsg[key] + '<br>';  
    }  
    document.getElementById('errorMsg').innerHTML = msg;  
}  
</script>  
<script type="text/javascript">  
FormValid.showError = function(errMsg,errName) {  
    for (key in FormValid.allName) {  
        document.getElementById('errMsg_'+FormValid.allName[key]).innerHTML =   
 
'';  
    }  
    for (key in errMsg) {  
        document.getElementById('errMsg_'+errName[key]).innerHTML = errMsg  
 
[key];  
    }  
}  
</script>  
</head>  
 
<body><h2>FormValid Demo3 自定义错误信息显示方式2</h2>  
<table width="400" border="0" cellpadding="3" cellspacing="0">  
<form id="form1" name="form1" method="post" onsubmit="return validator(this)" action="">  
  <tr>  
    <td width="100">用户名:</td>  
    <td><input name="username" type="text" valid="required" errmsg="用户名不能为空!"   
 
/><span id="errMsg_username" style="color:#FF0000"></span></td>  
  </tr>  
  <tr>  
    <td>密码</td>  
    <td><input name="passwd" type="password" id="passwd" valid="required" errmsg="密码  
 
不能为空!" /><span id="errMsg_passwd" style="color:#FF0000"></span></td>  
  </tr>  
  <tr>  
    <td>重复密码</td>  
    <td><input name="passwd2" type="password" id="passwd2" valid="eqaul"   
 
eqaulName="passwd" errmsg="两次密码不同!" /><span id="errMsg_passwd2"   
 
style="color:#FF0000"></span></td>  
  </tr>  
  <tr>  
    <td>Email</td>  
    <td><input name="Email" type="text" id="Email" valid="required|isEmail" errmsg="Email不  
 
能为空|Email格式不对!" /><span id="errMsg_Email" style="color:#FF0000"></span></td>  
  </tr>  
  <tr>  
    <td>手机</td>  
    <td><input name="mobile" type="text" id="mobile" valid="isMobile" errmsg="手机格式不  
 
对!" /><span id="errMsg_mobile" style="color:#FF0000"></span></td>  
  </tr>  
  <tr>  
    <td>生日</td>  
    <td><input name="birthday" type="text" id="birthday" valid="isDate" errmsg="生日格式不  
 
对!" /><span id="errMsg_birthday" style="color:#FF0000"></span></td>  
  </tr>  
  <tr>  
    <td>&nbsp;</td>  
    <td><input type="submit" name="Submit" value="提交" /></td>  
  </tr>  
</form>  
</table>  
<div id="errorMsg" style="width:400px; color:#FF0000" align="center"> </div>  
</body>  
</html> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>FormValid Demo3 自定义错误信息显示方式2</title>
<script language="JavaScript" type="text/javascript">
var FormValid = function(frm) {
    this.frm = frm;
    this.errMsg = new Array();
this.errName = new Array();
  
    this.required = function(inputObj) {
        if (typeof(inputObj) == "undefined" || inputObj.value.trim() == "") {
            return false;
        }
return true;
    }
   
    this.eqaul = function(inputObj, formElements) {
var fstObj = inputObj;
var sndObj = formElements[inputObj.getAttribute('eqaulName')];

        if (fstObj != null && sndObj != null) {
            if (fstObj.value != sndObj.value) {
               return false;
            }
        }
return true;
    }

    this.gt = function(inputObj, formElements) {
var fstObj = inputObj;
var sndObj = formElements[inputObj.getAttribute('eqaulName')];

        if (fstObj != null && sndObj != null && fstObj.value.trim()!='' && sndObj.value.trim()!='')

{
            if (fstObj.value <= sndObj.value) {
                 return false;
            }
        }
return true;
    }

this.compare = function(inputObj, formElements) {
var fstObj = inputObj;
var sndObj = formElements[inputObj.getAttribute('objectName')];
        if (fstObj != null && sndObj != null && fstObj.value.trim()!='' && sndObj.value.trim()!='')

{
            if (!eval('fstObj.value' + inputObj.getAttribute('operate') + 'sndObj.value')) {
                 return false;
            }
        }
return true;
}

this.limit = function (inputObj) {
var len = inputObj.value.length;
if (len) {
var minv = inputObj.getAttribute('min');
var maxv = inputObj.getAttribute('max');
minv = minv || 0;
maxv = maxv || Number.MAX_VALUE;
return minv <= len && len <= maxv;
}
return true;
}

this.range = function (inputObj) {
var val = parseInt(inputObj.value);
if (inputObj.value) {
var minv = inputObj.getAttribute('min');
var maxv = inputObj.getAttribute('max');
minv = minv || 0;
maxv = maxv || Number.MAX_VALUE;

return minv <= val && val <= maxv;
}
return true;
}

this.requireChecked = function (inputObj) {
var minv = inputObj.getAttribute('min');
var maxv = inputObj.getAttribute('max');
minv = minv || 1;
maxv = maxv || Number.MAX_VALUE;

var checked = 0;
var groups = document.getElementsByName(inputObj.name);

for(var i=0;i<groups.length;i++) {
if(groups[i].checked) checked++;

}
return minv <= checked && checked <= maxv;
}

this.filter = function (inputObj) {
var value = inputObj.value;
var allow = inputObj.getAttribute('allow');
if (value.trim()) {
return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g,

allow.split(/\s*,\s*/).join("|")), "gi").test(value);
}
return true;
}

this.isNo = function (inputObj) {
var value = inputObj.value;
var noValue = inputObj.getAttribute('noValue');
return value!=noValue;
}
    this.checkReg = function(inputObj, reg, msg) {
        inputObj.value = inputObj.value.trim();

        if (inputObj.value == '') {
            return;
        } else {
            if (!reg.test(inputObj.value)) {
this.addErrorMsg(inputObj.name,msg);
}
        }
    }

    this.passed = function() {
        if (this.errMsg.length > 0) {
            FormValid.showError(this.errMsg,this.errName);
            frt = document.getElementsByName(this.errName[0])[0];

if (frt.type!='radio' && frt.type!='checkbox') {
frt.focus();
}
            return false;
        } else {
          return true;
        }
    }

    this.addErrorMsg = function(name,str) {
        this.errMsg.push(str);
this.errName.push(name);
    }

    this.addAllName = function(name) {
FormValid.allName.push(name);
    }

}
FormValid.allName = new Array();
FormValid.showError = function(errMsg) {
var msg = "";
for (i = 0; i < errMsg.length; i++) {
msg += "- " + errMsg[i] + "\n";
}

alert(msg);
}
function validator(frm) {
var formElements = frm.elements;
var fv = new FormValid(frm);

for (var i=0; i<formElements.length;i++) {
var validType = formElements[i].getAttribute('valid');
var errorMsg = formElements[i].getAttribute('errmsg');
if (validType==null) continue;
fv.addAllName(formElements[i].name);

var vts = validType.split('|');
var ems = errorMsg.split('|');
for (var j=0; j<vts.length; j++) {
var curValidType = vts[j];
var curErrorMsg = ems[j];

switch (curValidType) {
case 'isNumber':
case 'isEmail':
case 'isPhone':
case 'isMobile':
case 'isIdCard':
case 'isMoney':
case 'isZip':
case 'isQQ':
case 'isInt':
case 'isEnglish':
case 'isChinese':
case 'isUrl':
case 'isDate':
case 'isTime':
fv.checkReg(formElements[i],RegExps

[curValidType],curErrorMsg);
break;
case 'regexp':
fv.checkReg(formElements[i],new RegExp

(formElements[i].getAttribute('regexp'),"g"),curErrorMsg);
break;
case 'custom':
if (!eval(formElements[i].getAttribute('custom')

+'(formElements[i],formElements)')) {
fv.addErrorMsg(formElements

[i].name,curErrorMsg);
}
break;
default :
if (!eval('fv.'+curValidType+'(formElements

[i],formElements)')) {
fv.addErrorMsg(formElements

[i].name,curErrorMsg);
}
break;
}
}
}
return fv.passed();
}
String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, "");
}
var RegExps = function(){};
RegExps.isNumber = /^[-\+]?\d+(\.\d+)?$/;
RegExps.isEmail = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]

{2,4}|[0-9]{1,3})(\]?)/;
RegExps.isPhone = /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d

{1,4})?$/;
RegExps.isMobile = /^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/;
RegExps.isIdCard = /(^\d{15}$)|(^\d{17}[0-9Xx]$)/;
RegExps.isMoney = /^\d+(\.\d+)?$/;
RegExps.isZip = /^[1-9]\d{5}$/;
RegExps.isQQ = /^[1-9]\d{4,10}$/;
RegExps.isInt = /^[-\+]?\d+$/;
RegExps.isEnglish = /^[A-Za-z]+$/;
RegExps.isChinese =  /^[\u0391-\uFFE5]+$/;
RegExps.isUrl = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
RegExps.isDate = /^\d{4}-\d{1,2}-\d{1,2}$/;
RegExps.isTime = /^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}$/;
</script>
<script type="text/javascript">
FormValid.showError = function(errMsg) {
var msg = '';
for (key in errMsg) {
msg += errMsg[key] + '<br>';
}
document.getElementById('errorMsg').innerHTML = msg;
}
</script>
<script type="text/javascript">
FormValid.showError = function(errMsg,errName) {
for (key in FormValid.allName) {
document.getElementById('errMsg_'+FormValid.allName[key]).innerHTML =

'';
}
for (key in errMsg) {
document.getElementById('errMsg_'+errName[key]).innerHTML = errMsg

[key];
}
}
</script>
</head>

<body><h2>FormValid Demo3 自定义错误信息显示方式2</h2>
<table width="400" border="0" cellpadding="3" cellspacing="0">
<form id="form1" name="form1" method="post" onsubmit="return validator(this)" action="">
  <tr>
    <td width="100">用户名:</td>
    <td><input name="username" type="text" valid="required" errmsg="用户名不能为空!"

/><span id="errMsg_username" style="color:#FF0000"></span></td>
  </tr>
  <tr>
    <td>密码</td>
    <td><input name="passwd" type="password" id="passwd" valid="required" errmsg="密码

不能为空!" /><span id="errMsg_passwd" style="color:#FF0000"></span></td>
  </tr>
  <tr>
    <td>重复密码</td>
    <td><input name="passwd2" type="password" id="passwd2" valid="eqaul"

eqaulName="passwd" errmsg="两次密码不同!" /><span id="errMsg_passwd2"

style="color:#FF0000"></span></td>
  </tr>
  <tr>
    <td>Email</td>
    <td><input name="Email" type="text" id="Email" valid="required|isEmail" errmsg="Email不

能为空|Email格式不对!" /><span id="errMsg_Email" style="color:#FF0000"></span></td>
  </tr>
  <tr>
    <td>手机</td>
    <td><input name="mobile" type="text" id="mobile" valid="isMobile" errmsg="手机格式不

对!" /><span id="errMsg_mobile" style="color:#FF0000"></span></td>
  </tr>
  <tr>
    <td>生日</td>
    <td><input name="birthday" type="text" id="birthday" valid="isDate" errmsg="生日格式不

对!" /><span id="errMsg_birthday" style="color:#FF0000"></span></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="Submit" value="提交" /></td>
  </tr>
</form>
</table>
<div id="errorMsg" style="width:400px; color:#FF0000" align="center"> </div>
</body>
</html>
  相关解决方案