使用JS组件实现带ToolTip验证框的实例代码

发布时间 - 2026-01-11 02:55:06    点击率:

本组件依赖JQuery

本人测试的JQuery 是1.8,

兼容IE8,IE9,谷歌,火狐等。

//验证输入框
function ValidateCompent(input){
  var _input = $(input).clone(true);
  _input.css("height",$(input).css("height"));
  _input.css("width", $(input).css("width"));
  var border =_input.css("border"); 
  this.successIconClass = "icon-tick";//验证通过时的样式
  this.validate = false;
  this.faileIconClass = "icon-times";//验证失败时的样式
  var $validateRoot = $('<div class="validate-v1-container"><div class="validate-v1-tooltip"></div></div>');
  var $tooltip = $validateRoot.children(".validate-v1-tooltip");
  var $input = _input;
  if($input != undefined){
    var maxWidth = $input.css("width");
    var maxHeight = $input.css("height");
    $validateRoot.css("display","inline");
    $validateRoot.css("position","relative");
    $validateRoot.css("width",maxWidth);
    $validateRoot.css("height",maxHeight);
    $tooltip.css("width",maxWidth);
    $tooltip.css("padding","0px 5px");
    $tooltip.css("position","absolute");
    $tooltip.css("top","0px");
    $tooltip.css("z-index","999999");
    $tooltip.css("background-color","white");
    $tooltip.css("border","solid 1px rgb(188,188,188)");
    $tooltip.css("left",parseInt(maxWidth) + 10+"px");
    $tooltip.hide();
    var validateOption = $input.attr("data-vali-option");
    if(validateOption != undefined){
      validateOption = JSON.parse(validateOption);
      var that = this;
      var regvali = new Array();
      $tooltip.hide();
      if(validateOption.length == 0){
        return;
      }
      for(var i = 0; i <validateOption.length;i++){
        var message = validateOption[i].message;
        var pattern = validateOption[i].pattern;
        var reg = new RegExp(pattern);
        var messageView = new ValidateMessage(message,that.faileIconClass);
        regvali.push({"reg":reg,"view":messageView});
        $tooltip.append(messageView.dom);
      }
      $tooltip.css("height",(parseInt(maxHeight) +15) * validateOption.length );
      $input.on("textchange focus",function(e){
        $tooltip.show();
        for(var i = 0 ; i < regvali.length; i++){
          if(regvali[i].reg.test($input.val())){
            regvali[i].view.setIconClass(that.successIconClass);
            regvali[i].view.dom.css("color","green");
          }else{
            regvali[i].view.setIconClass(that.faileIconClass);
            regvali[i].view.dom.css("color","red");
          }
        }
      })
      $input.on("blur", function(e) {
        $tooltip.hide();
        for(var i = 0 ; i < regvali.length; i++){
          if(regvali[i].reg.test($input.val())){
            regvali[i].view.setIconClass(that.successIconClass);
            $input.css("border",border);
            that.validate = true;
          }else{
            regvali[i].view.setIconClass(that.faileIconClass);
            $input.css("border","1px solid red");
            that.validate = false;
            break;
          }
        }
      });
      $validateRoot.append($input);
    }else{
      return;
    }
  }
  this.dom = function(){
    return $validateRoot;
  }
  function ValidateMessage(message,iconFontClass){
    var dom = $('<div class="validate-message"><span class="vticon"></span><span class="vmessage"></span></div>');
    var $icon = dom.children(".vticon");
    var $message = dom.children(".vmessage");
    $message.css("line-height","28px");
    $message.css("padding","5px 5px");
    $message.css("padding-right","10px");
    $message.css("word-break","break-all");
    $message.css("word-wrap","break-word");
    $message.css("font-size","14px");
    $message.css("position","relative");
    $message.css("z-index","999999");
    this.setIconClass = function(iconClass){
      $icon.removeClass();
      $icon.addClass("vticon");
      $icon.addClass(iconClass);
    }
    this.getIcon = function(){
      return $icon;
    }
    this.setMessageText = function(_message){
      $message.html(_message);
    }
    this.getMessageText = function(){
      return $message;
    }
    this.setIconClass(iconFontClass);
    this.setMessageText(message);
    this.dom = dom;
  }
  $validateRoot.insertAfter($(input));
  $(input).remove();
}

以下是HTML代码

<input id="test" data-vali-option='[{"pattern":"[1-9]+","message":"只能输入1-9的数"},{"pattern":"[a-z]+","message":"只能输入a-z的数"}]' />

使用方法如下

$(function(){
  var c = new ValidateCompent("#test");
});

依赖JQuery,

另外附上JQuery textchange事件的代码,textchange代码放在JQuery之后,在使用方法之前。

/**
 * jQuery "splendid textchange" plugin
 * http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html
 *
 * (c) 2013 Ben Alpert, released under the MIT license
 */
(function($) {
var testNode = document.createElement("input");
var isInputSupported = "oninput" in testNode && 
  (!("documentMode" in document) || document.documentMode > 9);
var hasInputCapabilities = function(elem) {
  // The HTML5 spec lists many more types than `text` and `password` on
  // which the input event is triggered but none of them exist in IE 8 or
  // 9, so we don't check them here.
  // TODO: <textarea> should be supported too but IE seems to reset the
  // selection when changing textarea contents during a selectionchange
  // event so it's not listed here for now.
  return elem.nodeName === "INPUT" &&
    (elem.type === "text" || elem.type === "password");
};
var activeElement = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
 * (For old IE.) Replacement getter/setter for the `value` property that
 * gets set on the active element.
 */
var newValueProp = {
  get: function() {
    return activeElementValueProp.get.call(this);
  },
  set: function(val) {
    activeElementValue = val;
    activeElementValueProp.set.call(this, val);
  }
};
/**
 * (For old IE.) Starts tracking propertychange events on the passed-in element
 * and override the value property so that we can distinguish user events from
 * value changes in JS.
 */
var startWatching = function(target) {
  activeElement = target;
  activeElementValue = target.value;
  activeElementValueProp = Object.getOwnPropertyDescriptor(
      target.constructor.prototype, "value");
  Object.defineProperty(activeElement, "value", newValueProp);
  activeElement.attachEvent("onpropertychange", handlePropertyChange);
};
/**
 * (For old IE.) Removes the event listeners from the currently-tracked
 * element, if any exists.
 */
var stopWatching = function() {
 if (!activeElement) return;
 // delete restores the original property definition
 delete activeElement.value;
 activeElement.detachEvent("onpropertychange", handlePropertyChange);
 activeElement = null;
 activeElementValue = null;
 activeElementValueProp = null;
};
/**
 * (For old IE.) Handles a propertychange event, sending a textChange event if
 * the value of the active element has changed.
 */
var handlePropertyChange = function(nativeEvent) {
  if (nativeEvent.propertyName !== "value") return;
  var value = nativeEvent.srcElement.value;
  if (value === activeElementValue) return;
  activeElementValue = value;
  $(activeElement).trigger("textchange");
};
if (isInputSupported) {
  $(document)
    .on("input", function(e) {
      // In modern browsers (i.e., not IE 8 or 9), the input event is
      // exactly what we want so fall through here and trigger the
      // event...
      if (e.target.nodeName !== "TEXTAREA") {
        // ...unless it's a textarea, in which case we don't fire an
        // event (so that we have consistency with our old-IE shim).
        $(e.target).trigger("textchange");
      }
    });
} else {
  $(document)
    .on("focusin", function(e) {
      // In IE 8, we can capture almost all .value changes by adding a
      // propertychange handler and looking for events with propertyName
      // equal to 'value'.
      // In IE 9, propertychange fires for most input events but is buggy
      // and doesn't fire when text is deleted, but conveniently,
      // selectionchange appears to fire in all of the remaining cases so
      // we catch those and forward the event if the value has changed.
      // In either case, we don't want to call the event handler if the
      // value is changed from JS so we redefine a setter for `.value`
      // that updates our activeElementValue variable, allowing us to
      // ignore those changes.
      if (hasInputCapabilities(e.target)) {
        // stopWatching() should be a noop here but we call it just in
        // case we missed a blur event somehow.
        stopWatching();
        startWatching(e.target);
      }
    })
    .on("focusout", function() {
      stopWatching();
    })
    .on("selectionchange keyup keydown", function() {
      // On the selectionchange event, e.target is just document which
      // isn't helpful for us so just check activeElement instead.
      //
      // 90% of the time, keydown and keyup aren't necessary. IE 8 fails
      // to fire propertychange on the first input event after setting
      // `value` from a script and fires only keydown, keypress, keyup.
      // Catching keyup usually gets it and catching keydown lets us fire
      // an event for the first keystroke if user does a key repeat
      // (it'll be a little delayed: right before the second keystroke).
      // Other input methods (e.g., paste) seem to fire selectionchange
      // normally.
      if (activeElement && activeElement.value !== activeElementValue) {
        activeElementValue = activeElement.value;
        $(activeElement).trigger("textchange");
      }
    });
}
})(jQuery);

获取验证结果

$(function(){
  var c = new ValidateCompent("#test");
  $("#test").click(function(){
    console.log(c.validate);
  });
});

自定义显示方案

$(function(){
  var c = new ValidateCompent("#test");
  $("#test").click(function(){
    console.log(c.validate);
  });
  c.dom().addClass("你的样式类");
});

设置图标字体样式

$(function(){
  var c = new ValidateCompent("#test");
  $("#test").click(function(){
    console.log(c.validate);
  });
  c.successIconClass = "";//成功时的样式
  c.faileIconClass = "";//失败时的样式
});

效果图如下

分别是成功,部分成功,全部失败选中,未选中的样式效果,(勾叉是用的字体css,建议自行寻找字体替代)

总结

以上所述是小编给大家介绍的使用JS组件实现带ToolTip验证框的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!


# js  # 组件  # tooltip  # 验证框  # jQuery悬停文字提示框插件jquery.tooltipster.js用法示例【附demo源码下载  # ToolTip 通过Js实现代替超链接中的title效果  # jquery.cvtooltip.js 基于jquery的气泡提示插件  # 轻量级 JS ToolTip提示效果  # js验证框架之RealyEasy验证详解  # 非常实用的js验证框架实现源码 附原理方法  # 手把手教你自己写一个js表单验证框架的方法  # 小编  # 放在  # 在此  # 给大家  # 自定义  # 火狐  # 所述  # 给我留言  # 感谢大家  # 输入框  # 方法如下  # 疑问请  # 有任何  # break  # blur  # red  # setIconClass  # green  # val  # word 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel的契約(Contracts)是什么_深入理解Laravel Contracts与依赖倒置  jimdo怎样用html5做选项卡_jimdo选项卡html5实现与切换效果【指南】  中国移动官方网站首页入口 中国移动官网网页登录  Laravel如何生成PDF或Excel文件_Laravel文档导出工具与使用教程  Laravel的路由模型绑定怎么用_Laravel Route Model Binding简化控制器逻辑  php485函数参数是什么意思_php485各参数详细说明【介绍】  Laravel怎么进行数据库事务处理_Laravel DB Facade事务操作确保数据一致性  做企业网站制作流程,企业网站制作基本流程有哪些?  如何获取PHP WAP自助建站系统源码?  如何破解联通资金短缺导致的基站建设难题?  无锡营销型网站制作公司,无锡网选车牌流程?  如何在七牛云存储上搭建网站并设置自定义域名?  Laravel怎么集成Vue.js_Laravel Mix配置Vue开发环境  如何快速启动建站代理加盟业务?  Mybatis 中的insertOrUpdate操作  使用C语言编写圣诞表白程序  通义万相免费版怎么用_通义万相免费版使用方法详细指南【教程】  详解Android——蓝牙技术 带你实现终端间数据传输  如何在云主机快速搭建网站站点?  哪家制作企业网站好,开办像阿里巴巴那样的网络公司和网站要怎么做?  Laravel如何实现事件和监听器?(Event & Listener实战)  使用Dockerfile构建java web环境  Android自定义控件实现温度旋转按钮效果  简历在线制作网站免费版,如何创建个人简历?  Chrome浏览器标签页分组怎么用_谷歌浏览器整理标签页技巧【效率】  bing浏览器学术搜索入口_bing学术文献检索地址  百度浏览器如何管理插件 百度浏览器插件管理方法  图册素材网站设计制作软件,图册的导出方式有几种?  如何用VPS主机快速搭建个人网站?  nodejs redis 发布订阅机制封装实现方法及实例代码  Laravel Fortify是什么,和Jetstream有什么关系  长沙企业网站制作哪家好,长沙水业集团官方网站?  打造顶配客厅影院,这份100寸电视推荐名单请查收  Edge浏览器提示“由你的组织管理”怎么解决_去除浏览器托管提示【修复】  Laravel任务队列怎么用_Laravel Queues异步处理任务提升应用性能  如何基于云服务器快速搭建个人网站?  EditPlus中的正则表达式 实战(2)  高端建站如何打造兼具美学与转化的品牌官网?  IOS倒计时设置UIButton标题title的抖动问题  Python函数文档自动校验_规范解析【教程】  制作电商网页,电商供应链怎么做?  Laravel怎么实现模型属性转换Casting_Laravel自动将JSON字段转为数组【技巧】  java ZXing生成二维码及条码实例分享  微信推文制作网站有哪些,怎么做微信推文,急?  如何在景安云服务器上绑定域名并配置虚拟主机?  Laravel怎么实现微信登录_Laravel Socialite第三方登录集成  网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?  非常酷的网站设计制作软件,酷培ai教育官方网站?  Laravel如何实现模型的全局作用域?(Global Scope示例)  如何在 Telegram Web View(iOS)中防止键盘遮挡底部输入框