Javascript实现前台校验

function valid(theForm)
{
    var ReBool = true;
    var obj = theForm || event.srcElement;
 var count = obj.elements.length;
 for(var i=count-1;i>=0;i--)
 {
  with(obj.elements[i])
  {
   var _reg = getAttribute("reg");
   var _mes = getAttribute("msg");
   if(_reg != null)
   {
       var lastNode = obj.elements[i].parentNode.childNodes[obj.elements[i].parentNode.childNodes.length-1];
       if(!obj.elements[i].value.match(_reg))
          {      
              var span = document.createElement("span");
              span.id = "__ErrorMessagePanel";
        span.style.color = "red";
        span.innerHTML = _mes;                   
        obj.elements[i].parentNode.appendChild(span);
        ReBool = false;
        obj.elements[i].focus();
          }
          if(lastNode != obj.elements[i])
          {            
                    obj.elements[i].parentNode.removeChild(lastNode);
          }
   }
  }
 }
 if(ReBool == false)
     alert('请正确填写数据!');
 return ReBool;
}

 

在需要校验的TextBox里加上正则表达式和错误时显示的信息,例如" msg='不能为空' reg='^[/S]+$'  ",然后在按钮里加上" OnClientClick="return valid(aspnetForm)" "即可.效果如图所示:

你可能感兴趣的:(Javascript)