欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

从阿里妈妈发现的几个不错的表单验证函数

程序员文章站 2023-01-01 18:54:54
//-------- // 检查当前浏览器是否为netscape //-------- function isnetscape(){  &nb...
//--------
// 检查当前浏览器是否为netscape
//--------
function isnetscape(){
    app=navigator.appname.substring(0,1);
    if (app=='n') return true;
    else {return false;}
}

//--------
// 保存当前form表单(仅适用于ie浏览器)
//--------
function formsavecheck(filename){
    if(isnetscape()){alert("sorry, these function is not supported")}    
    else document.execcommand('saveas',null,filename)
}

//--------
// 校验数据的合法性
//--------
function isvalidreg( chars){
    var re=/<|>|\[|\]|\{|\}|『|』|※|○|●|◎|§|△|▲|☆|★|◇|◆|□|▼|㊣|﹋|⊕|⊙|〒|ㄅ|ㄆ|
ㄇ|ㄈ|ㄉ|ㄊ|ㄋ|ㄌ|ㄍ|ㄎ|ㄏ|ㄐ|ㄑ|ㄒ|ㄓ|ㄔ|ㄕ|ㄖ|ㄗ|ㄘ|ㄙ|ㄚ|ㄛ|ㄜ|ㄝ|ㄞ|ㄟ|ㄢ|ㄣ|ㄤ|ㄥ|ㄦ|ㄧ|ㄨ|ㄩ
|■|▄|▆|\*|@|#|\^|\\/;
    if (re.test( chars) == true) {
        return false;
    }else{
        return true;
    }    
}

//--------
// 检查数据的长度是否合法
//--------
function isvalidlength(chars, len) {
    if (chars.length > len) {
        return false;
    }
    return true;
}

//--------
// 校验url的合法性
//--------
function isvalidurl( chars ) {
    //var re=/^([hh][tt]{2}[pp]:\/\/|[hh][tt]{2}[pp][ss]:\/\/)((((\w+(-*\w*)+)\.)+((com)|
(net)|(edu)|(gov)|(org)|(biz)|(aero)|(coop)|(info)|(name)|(pro)|(museum))(\.([a-z]{2}))?)|((\w+(-
*\w*)+)\.(cn)))$/;
    var re=/^([hh][tt]{2}[pp]:\/\/|[hh][tt]{2}[pp][ss]:\/\/)(\s+\.\s+)$/;
    //var re=/^([hh][tt]{2}[pp]:\/\/|[hh][tt]{2}[pp][ss]:\/\/)(((((\w+(-*\w*)+)\.)+((com)|
(net)|(edu)|(gov)|(org)|(biz)|(aero)|(coop)|(info)|(name)|(pro)|(museum)|(cn)|(tv)|(hk))(\.([a-z]
{2}))?)|((\w+(-*\w*)+)\.(cn)))((\/|\?)\s*)*)$/;
    if (!isnull(chars)) {
        chars = jstrim(chars);
        if (chars.match(re) == null)
            return false;
        else
            return true;
    }
    return false;
}

//--------
// 校验数字的合法性
//--------
function isvaliddecimal( chars ) {
    var re=/^\d*\.?\d{1,2}$/;
    if (chars.match(re) == null)
        return false;
    else
        return true;
}

//--------
// 校验数字的合法性
//--------
function isnumber( chars ) {
    var re=/^\d*$/;
    if (chars.match(re) == null)
        return false;
    else
        return true;
}

//--------
// 校验邮编的合法性
//--------
function isvalidpost( chars ) {
    var re=/^\d{6}$/;
    if (chars.match(re) == null)
        return false;
    else
        return true;
}

//--------
// 去掉数据的首尾空字符
//--------
function jstrim(value){
  return value.replace(/(^\s*)|(\s*$)/g,"");
}

//--------
// 校验数据是否为空(当数据为空字符时也为null)
//--------
function isnull( chars ) {
    if (chars == null)
        return true;
    if (jstrim(chars).length==0)
        return true;
    return false;
}

//--------
// 校验email的合法性
//--------
function checkemail (fieldname, bmsg) 
{
    var emailstr = fieldname.value;

    var emailpat=/^(.+)@(.+)$/
    var specialchars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    var validchars="\[^\\s" + specialchars + "\]"
    var quoteduser="(\"[^\"]*\")"
    var ipdomainpat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
    var atom=validchars + '+'
    var word="(" + atom + "|" + quoteduser + ")"
    var userpat=new regexp("^" + word + "(\\." + word + ")*$")
    var domainpat=new regexp("^" + atom + "(\\." + atom +")*$")

    var matcharray=emailstr.match(emailpat)
    if (matcharray==null) 
    {
        if (bmsg) alert("email address seems incorrect (check @ and .'s)")
        return false
    }
    var user=matcharray[1]
    var domain=matcharray[2]

    // see if "user" is valid 
    if (user.match(userpat)==null) 
    {
        if (bmsg) alert("the email address seems incorrect.")
        // fieldname.focus();
        return false
    }

    /* if the e-mail address is at an ip address (as opposed to a symbolic
       host name) make sure the ip address is valid. */
    var iparray=domain.match(ipdomainpat)
    if (iparray!=null) 
    {
        for (var i=1;i<=4;i++)
        {
            if (iparray[i]>255)
            {
                if (bmsg) alert("destination ip address is invalid!")
                return false
            }
        }
        return true
    }

    // domain is symbolic name
    var domainarray=domain.match(domainpat)
    if (domainarray==null) 
    {
        if (bmsg) alert("the domain name doesn't seem to be valid.")
        return false
    }

    /* domain name seems valid, but now make sure that it ends in a
    three-letter word (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding 
    the domain or country. */

    var atompat=new regexp(atom,"g")
    var domarr=domain.match(atompat)
    var len=domarr.length
    if (domarr[domarr.length-1].length<2 || domarr[domarr.length-1].length>3) 
    {
        // the address must end in a two letter or three letter word.
        if (bmsg) alert("the address must end in a three-letter domain, or two letter country.")
        return false
    }

    // make sure there's a host name preceding the domain.
    if (len<2)
    {
        if (bmsg) alert("this address is missing a hostname!")
        return false
    }

    // if we've got this far, everything's valid!
    return true;
}

//--------
// 判断是否为闰年
//--------
function isleapyear(year){
  if (year % 4 != 0)
    return false;
  if (year % 400 == 0)
    return true;
  if (year % 100 == 0)
    return false;
  return true;
}

//--------
// 校验日期的合法性
//--------
function validatedate(day,month,year)
{
    if ((day<=0)||(month<=0)||(year<=0))
        return false;

    if ((month>=1)&&(month<=12)) {
        if (month == 2) {
            if (isleapyear(year)) {
                if (day<=29) 
                    return true;
            } else {
                if (day<=28)
                    return true;
                else
                    return false;
            }
        } else if ((month==4)||(month==6)||(month==9)||(month==11)) {
            if (day<=30)
                return true;
            else
                return false;
        } else {
            if (day<=31)
                return true;
            else
                return false;
        }
    }

    return false;
}

//--------
// 判断数据是否包含都是single byte
//--------
function issinglebytestring(str)
{
   var rc = true;
   var j = 0, i = 0;
   for (i=0; i<str.length; i++) {
     j = str.charcodeat(i);
     if (j>=128) {
       rc = false;
       break;
     }
   }
   return rc;
}

var submitevent = true;
function checkdoublesubmit(){
    return submitevent;
}

//--------
// 弹出窗口
// 参数:url-弹出窗口显示url的内容
//       w-弹出窗口的宽度
//       h-弹出窗口的高度
//       iscenter-控制弹出窗口是否在屏幕*显示,值为true/false
//       isresizable-控制弹出窗口是否可以改变大小,值为true/false
//       isscroll-控制弹出窗口是否有滚动条,值为true/false
//--------
function popupwindow(url,w,h,iscenter,isresizable,isscroll) {
    if (isnull(url)) return;
    var scrleft = 0;
    var scrtop = 0;
    var scroll = "no";
    var resize = "no";
    if (iscenter) {
        scrleft = (screen.width-w)/2;
        scrtop = (screen.height-h)/2;
    }
    if (isresizable) resize="yes";
    if (isscroll) scroll = "yes";
    window.open(url, 'popupwindow', 
'height='+h+',width='+w+',top='+scrtop+',left='+scrleft+',toolbar=no,menubar=no,scrollbars='+scrol
l+',resizable='+resize+',location=no,status=no');
}

//--------
// 弹出窗口
// 参数:url-弹出窗口显示url的内容
//       w-弹出窗口的宽度
//       h-弹出窗口的高度
//       iscenter-控制弹出窗口是否在屏幕*显示,值为true/false
//       isresizable-控制弹出窗口是否可以改变大小,值为true/false
//       ismodal-控制弹出窗口是否为模式或非模式对话框,值为ture/false
//--------
function popupmodalwindow(url,w,h,iscenter,isresizable,ismodal) {
    if (isnull(url)) return;
    var scrleft = 0;
    var scrtop = 0;
    var resize = "no";
    var cnt = "no";
    if (iscenter) {
        cnt="yes";
        scrleft = (screen.width-w)/2;
        scrtop = (screen.height-h)/2;
    }
    if (isresizable) resize="yes";
    if (ismodal)
        window.showmodaldialog(url, 'popupwindow', 
'dialogwidth:'+w+'px;dialogheight:'+h+'px;dialogleft:'+scrleft+'px;dialogtop:'+scrtop+'px;center:'
+cnt+';help:no;resizable:'+resize+';status:no');
    else
        window.showmodelessdialog(url, 'popupwindow', 
'dialogwidth:'+w+'px;dialogheight:'+h+'px;dialogleft:'+scrleft+'px;dialogtop:'+scrtop+'px;center:'
+cnt+';help:no;resizable:'+resize+';status:no');
}

//--------
// 弹出窗口
// 参数:url-弹出窗口显示url的内容
//       w-弹出窗口的宽度
//       h-弹出窗口的高度
//       iscenter-控制弹出窗口是否在屏幕*显示,值为true/false
//       isresizable-控制弹出窗口是否可以改变大小,值为true/false
//       isscroll-控制弹出窗口是否有滚动条,值为true/false
//--------
function openwindowcenter(urll,w,h){
  var top=(window.screen.height-h)/2;
  var left=(window.screen.width-w)/2;
  var param='toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no, status=no,top=';
  param=param+top;
  param=param+',left=';
  param=param+left;
  param=param+',height='+h;
  param=param+',width='+w;
  var w=window.open (urll,"",param)
  if(w!=null && typeof(w)!="undefined"){
        w.focus();
  }
}

<script language="javascript">
function encodehtmlfortext(text){
  text = text.replace(new regexp("&","gm"),"&");
  text = text.replace(new regexp("<","gm"),"<");
  text = text.replace(new regexp(">","gm"),">");
  text = text.replace(new regexp("\'","gm"),"'");
  text = text.replace(new regexp("\"","gm"),""");
  return text;
}
function encodehtmlforurl(url){
  url = url.replace(new regexp("<","gm"),"<");
  url = url.replace(new regexp(">","gm"),">");
  url = url.replace(new regexp("\'","gm"),"'");
  url = url.replace(new regexp("\"","gm"),""");
  return url;
}
function title_url_change(oipt) {
  if(oipt){
      var cnt = oipt.value.length;
    if(cnt<17){
        $i("cnttitle").style.color="blue";
        $i("cnttitle").innerhtml="(您已输入"+cnt+"字)";
    }else{
        $i("cnttitle").style.color="red";
        $i("cnttitle").innerhtml="(文本超长!您已输入"+cnt+"字)";
    }
  }
  var title = $i('_fmm.t._0.ti').value;
  var clickurl = $i('_fmm.t._0.cl').value;
  title = encodehtmlfortext(title);
  clickurl = encodehtmlforurl(clickurl);
  $i('adtitle').innerhtml = '<a href='+clickurl+'>'+title+'</a>';
}
function title_change() {
  var title = $i('_fmm.t._0.ti').value;
  title = encodehtmlfortext(title);
  $i('adtitle').innerhtml = title;
}
function description_change(oipt) {
  if(oipt){
      var cnt = oipt.value.length;
    if(cnt<33){
        $i("cntdesc").style.color="blue";
        $i("cntdesc").innerhtml="(您已输入"+cnt+"字)";
    }else{
        $i("cntdesc").style.color="red";
        $i("cntdesc").innerhtml="(文本超长!您已输入"+cnt+"字)";
    }
  }
  var desc = $i('_fmm.t._0.d').value;
  desc = encodehtmlfortext(desc);
  $i('addesc').innerhtml = desc;
}
function dispurl_change() {
  var dispurl = $i('_fmm.t._0.di').value;
  dispurl = encodehtmlforurl(dispurl);
  $i('addispurl').innerhtml = dispurl;
}
function linkurl_change() {
  var clickurl = $i('_fmm.t._0.cl').value;
  clickurl = encodehtmlforurl(clickurl);
  $i('adclickurl').innerhtml = clickurl;
}
function check_count($str){
if (!$str) return 0;
var $c=0;
for (var $i=0;$i<$str.length;$i++){
   if ($str.charcodeat($i) > 255){
        $c++;
        $c++;
    }else
        $c++;
}
return $c;
}
function validation() {
    $i('_fmm.t._0.n').value = jstrim($i('_fmm.t._0.n').value);
    $i('_fmm.t._0.ti').value = jstrim($i('_fmm.t._0.ti').value);
    $i('_fmm.t._0.d').value = jstrim($i('_fmm.t._0.d').value);
    $i('_fmm.t._0.di').value = jstrim($i('_fmm.t._0.di').value);
    $i('_fmm.t._0.cl').value = jstrim($i('_fmm.t._0.cl').value);

    var adname = $i('_fmm.t._0.n').value;
    var adtitle = $i('_fmm.t._0.ti').value;
    var addescription = $i('_fmm.t._0.d').value;
    var addispurl = $i('_fmm.t._0.di').value;
    var adclickurl = $i('_fmm.t._0.cl').value;
    var msg="";

    $i('_fmm.t._0.t').value = jstrim($i('_fmm.t._0.t').value);

    var tags = $i('_fmm.t._0.t').value;

    if(!isvalidreg(tags)){
        msg=msg+"关键词包含非法字符!\n";
    }
    if(!isvalidlength(tags,32)){
        msg=msg+"您输入的关键词长度超过限制!\n"
    }

    if(isnull(adname)){
        msg=msg+"请输入广告名称!\n";
    }
    if(!isvalidreg(adname)){
        msg=msg+"广告名称包含非法字符!\n";
    }
    if(!isvalidlength(adname,16)){
        msg=msg+"输入广告名称长度超过限制!\n"
    }
    if(isnull(adtitle)){
        msg=msg+"请输入标题内容!\n";
    }
    if(!isvalidlength(adtitle,16)){
        msg=msg+"输入标题长度超过限制!\n";
    }
    if(!isvalidreg(adtitle)){
        msg=msg+"标题内容包含非法字符!\n";
    }
    if(isnull(addescription)){
        msg=msg+"请输入描述内容!\n";
    }
    if(!isvalidlength(addescription,32)){
        msg=msg+"输入描述长度超过限制!\n";
    }
    if(!isvalidreg(addescription)){
        msg=msg+"描述内容包含非法字符!\n";
    }
    if(isnull(addispurl)){
        msg=msg+"请输入显示网址内容!\n";
    }
    if(!isvalidlength(addispurl,1024)){
        msg=msg+"输入显示网址长度超过限制!\n";
    }
    if(!isvalidurl(addispurl)){
        msg=msg+"显示网址输入不合法!\n";
    }
    if(isnull(adclickurl)){
        msg=msg+"请输入链接网址内容!\n";
    }
    if(!isvalidlength(adclickurl,512)){
        msg=msg+"输入链接网址长度超过限制!\n";
    }
    if(!isvalidurl(adclickurl)){
        msg=msg+"链接网址输入不合法!\n";
    }
    if(gethostname(adclickurl)!=gethostname(addispurl)){
        msg=msg+"显示url必须与链接url位于同一域名下\n";
    }
    if(!isnull(msg)){
        alert(msg);
        return false;
    }
    return true;
}

function gethostname(a){
    a = a.tolowercase();
    var headlength = 0;
    if(a.indexof("http://")==0){
        headlength = 7;
    }else if(a.indexof("https://")==0){
        headlength = 8;
    }
    a = a.substr(headlength);
    if(a.indexof("/")>-1){
        a = a.substr(0,a.indexof("/"));
    }
    return a;
}

function addconfirm(form) {
    var isvalidate = validation();
    if(isvalidate){
        form.submit();
    }else{
        return false;
    }
}
function dotest() {
    var adclickurl = $i('_fmm.t._0.cl').value;
    var msg = '';
    if(isnull(adclickurl)){
        msg=msg+"请输入链接网址内容!\n";
    }
    if(!isvalidlength(adclickurl,512)){
        msg=msg+"输入链接网址长度超过限制!\n";
    }
    if(!isvalidurl(adclickurl)){
        msg=msg+"链接网址输入不合法!\n";
    }
    if(!isnull(msg)){
        alert(msg);
        return false;
    }
    popup = window.open(adclickurl, 'popupnav', 
'width=400,height=300,left=480,top=250,resizable=1,scrollbars=yes');
    return false;
}
function doinit() {
    var dispurl = $i('_fmm.t._0.di');
    var clickurl = $i('_fmm.t._0.cl');
    if(clickurl.value == '') {
       clickurl.value = 'http://';
    }
    if(dispurl.value == '') {
       dispurl.value = 'http://';
    }
}
doinit();
</script>