使用jquery进行验证的常用功能

时间:2017-01-31 09:52:46

标签: javascript jquery html css twitter-bootstrap

我使用简单的代码来验证输入框是否为空,只是相应地显示check iconwarning icon

enter image description here

您可以在此处查看工作PLUNKER

问题:这组代码适用于一组Label:Input Box

想象一下,如果我们在整个网站上有多个输入控件。 我正在寻找一个相当普遍的解决方案。无需一遍又一遍地重复相同的HTML,CSS或JS代码集。 我知道很难避免一些重复,但想写更少重复的代码。



// Code goes here

$(document).ready(

  function() {
    $("#icon-id").hide();
    $("#input-id").keyup(function() {
      if ($("#input-id").val().length === 0) {
        $("#input-id").addClass("redBorder");
        $("#icon-id").addClass("icon-warning-sign");
        $("#icon-id").removeClass("icon-check");
        $("#icon-id").css("color", "red");
        $("#icon-id").show();
      } else {
        $("#input-id").removeClass("redBorder");
        $("#icon-id").removeClass("icon-warning-sign");
        $("#icon-id").addClass("icon-check");
        $("#icon-id").css("color", "green");
        $("#icon-id").show();
      }
    });
  });

  body {
    margin: 20px;
  }
  
  .input-container {
    width: 250px;
    position: relative;
  }
  
  .my-input {
    width: 100%;
  }
  
  .my-icon {
    position: absolute;
    right: 0px;
    color: red;
    top: 8px;
  }
  
  .redBorder {
    border: 1px solid red !important;
  }

<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body style="margin-top:55px;">

  <!-- validation check -->
  <div id="header" style="margin-bottom:20px;">
    <div id="validate-click"><a href="#">Enter Below</a></div>
  </div>

  <!-- input contianre -->
  <div class="form-group input-container">
    <input id="input-id" type="text" class="my-input" placeholder="Enter here">
    <i id="icon-id" class="icon-warning-sign my-icon"></i>
  </div>

</html>
&#13;
&#13;
&#13;

注意:请不要推荐任何第三方控件。

5 个答案:

答案 0 :(得分:2)

// Code goes here

$(document).ready(

  function() {
    $(".icon-id").hide();
    $(".input-id").keyup(function() {
      if ($(this).val().length === 0) {
        $(this).addClass("redBorder");
        $(this.parentElement).find("#icon-id").addClass("icon-warning-sign");
        $(this.parentElement).find("#icon-id").removeClass("icon-check");
        $(this.parentElement).find("#icon-id").css("color", "red");
        $(this.parentElement).find("#icon-id").show();
      } else {
        $(this).removeClass("redBorder");
        $(this.parentElement).find("#icon-id").removeClass("icon-warning-sign");
        $(this.parentElement).find("#icon-id").addClass("icon-check");
        $(this.parentElement).find("#icon-id").css("color", "green");
        $(this.parentElement).find("#icon-id").show();
      }
    });
  });
  body {
    margin: 20px;
  }
  
  .input-container {
    width: 250px;
    position: relative;
  }
  
  .my-input {
    width: 100%;
  }
  
  .my-icon {
    position: absolute;
    right: 0px;
    color:red;
    top: 8px;
  }
  .redBorder{
    border: 1px solid red !important;
  }
<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body style="margin-top:55px;">

  <!-- validation check -->
  <div id="header" style="margin-bottom:20px;">
    <div id="validate-click"><a href="#">Enter Below</a></div>
  </div>

  <!-- input contianre -->
  <div class="form-group input-container">
    <input id="input-id" type="text" class="my-input input-id" placeholder="Enter here">
    <i id="icon-id" class="icon-warning-sign my-icon icon-id"></i>
  </div>
  
  <div class="form-group input-container">
    <input id="input-id" type="text" class="my-input input-id" placeholder="Enter here">
    <i id="icon-id" class="icon-warning-sign my-icon icon-id"></i>
  </div>
  </body>

</html>

您可以尝试这样

答案 1 :(得分:2)

您可以使用类选择器代替id作为输入。并使用数据属性来选择好的图标。

live demo

您可以在下面看到一个示例:

  function() {
    $(".icon-class").hide();
    $(".input-class").keyup(function() {
      var idIcon = $(this).attr('data-id-icon');
      if ($(this).val().length === 0) {
        $(this).addClass("redBorder");
        $("#" + idIcon).addClass("icon-warning-sign");
        $("#" + idIcon).removeClass("icon-check");
        $("#" + idIcon).css("color", "red");
        $("#" + idIcon).show();
      } else {
        $(this).removeClass("redBorder");
        $("#" + idIcon).removeClass("icon-warning-sign");
        $("#" + idIcon).addClass("icon-check");
        $("#" + idIcon).css("color", "green");
        $("#" + idIcon).show();
      }
    });
  }
<input data-id-icon="icon-id-1" type="text" class="my-input input-class" placeholder="Enter here">
<i id="icon-id-1" class="icon-warning-sign my-icon"></i>
<input data-id-icon="icon-id-2" type="text" class="my-input input-class" placeholder="Enter here">
<i id="icon-id-2" class="icon-warning-sign my-icon-2"></i>

答案 2 :(得分:1)

将其设为jQuery插件:https://jsfiddle.net/1nxtt0Lk/ 我已将属性data-validate添加到您的<input />,因此我可以使用$('[data-validate'])在其上调用插件。

代码:

&#13;
&#13;
;( function( $, window, document, undefined ) {

	"use strict";

		var pluginName = "customValidator",
			defaults = {
				propertyName: "value"
			};

		function Plugin ( element, options ) {
			this.element = element;

			this.settings = $.extend( {}, defaults, options );
			this._defaults = defaults;
			this._name = pluginName;
			this.init();
		}

		$.extend( Plugin.prototype, {
			init: function() {
      	var $input = $(this.element);
      	var $icon = $input.parent().find('.my-icon');
				$icon.hide();
        $input.keyup(function() {
          if ($input.val().length === 0) {
            $input.addClass("redBorder");
           	$icon.addClass("icon-warning-sign");
            $icon.removeClass("icon-check");
            $icon.css("color", "red");
            $icon.show();
            console.log("empty");
          } else {
            $input.removeClass("redBorder");
            $icon.removeClass("icon-warning-sign");
            $icon.addClass("icon-check");
            $icon.css("color", "green");
            $icon.show();
            console.log("Not empty");
          }
        });
			},
		} );

		$.fn[ pluginName ] = function( options ) {
			return this.each( function() {
				if ( !$.data( this, "plugin_" + pluginName ) ) {
					$.data( this, "plugin_" +
						pluginName, new Plugin( this, options ) );
				}
			} );
		};

} )( jQuery, window, document );

$('[data-validate]').customValidator();
&#13;
body {
    margin: 20px;
  }
  
  .input-container {
    width: 250px;
    position: relative;
  }
  
  .my-input {
    width: 100%;
  }
  
  .my-icon {
    position: absolute;
    right: 0px;
    color: red;
    top: 8px;
  }
  
  .redBorder {
    border: 1px solid red !important;
  }
&#13;
<head>
  <script data-require="jquery@*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="style.css" />

</head>
<div class="form-group input-container">
    <input id="input-id" type="text" class="my-input" placeholder="Enter here" data-validate>
    <i id="icon-id" class="icon-warning-sign my-icon"></i>
 </div>
 <div class="form-group input-container">
    <input id="input-id2" type="text" class="my-input" placeholder="Enter here" data-validate>
    <i id="icon-id2" class="icon-warning-sign my-icon"></i>
 </div>
&#13;
&#13;
&#13;

PS:我使用插件样板作为基本脚本:https://github.com/jquery-boilerplate/jquery-boilerplate; 可在此处找到评论版本https://raw.githubusercontent.com/jquery-boilerplate/jquery-boilerplate/master/dist/jquery.boilerplate.js

其他答案建议使用类选择器迭代它们中的每一个。虽然该解决方案肯定会起作用,但我建议习惯于编写jQuery插件,因为从长远来看,它会使您的项目更加干净和易于阅读。

答案 3 :(得分:1)

您可以使用 my-inputmy-icon代替 id

keyup听众中,您可以使用$(this)来引用my-input$(this).next()来引用my-icon,因为图标是相邻input的兄弟

为简洁起见,也可以像这样链接你的函数:

$(this).next().removeClass("icon-warning-sign")
    .addClass("icon-check")
    .css("color", "green")
    .show();

见下面的演示:

&#13;
&#13;
// Code goes here

$(document).ready(function() {

  $(".my-icon").hide();
  $(".my-input").keyup(function() {
    if ($(this).val().length === 0) {
      $(this).addClass("redBorder");
      $(this).next().addClass("icon-warning-sign")
        .removeClass("icon-check")
        .css("color", "red")
        .show();
    } else {
      $(this).removeClass("redBorder");
      $(this).next().removeClass("icon-warning-sign")
        .addClass("icon-check")
        .css("color", "green")
        .show();
    }
  });
});
&#13;
body {
  margin: 20px;
}
.input-container {
  width: 250px;
  position: relative;
}
.my-input {
  width: 100%;
}
.my-icon {
  position: absolute;
  right: 0px;
  color: red;
  top: 8px;
}
.redBorder {
  border: 1px solid red !important;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
</head>

<body style="margin-top:55px;">

  <!-- validation check -->
  <div id="header" style="margin-bottom:20px;">
    <div id="validate-click"><a href="#">Enter Below</a>
    </div>
  </div>

  <!-- input contianre -->
  <div class="form-group input-container">
    <input id="input-id" type="text" class="my-input" placeholder="Enter here">
    <i id="icon-id" class="icon-warning-sign my-icon"></i>
  </div>

</html>
&#13;
&#13;
&#13;

答案 4 :(得分:1)

&#13;
&#13;
$(document).ready(
  function() {
    $(".my-input").keyup(function() {
      var $input = $(this).parent().find('input');
      var $icon = $(this).parent().find('i');
      if ($(this).val().length === 0) {
        $input.addClass("redBorder");
        $icon.addClass("icon-warning-sign").removeClass("icon-check").css("color", "red").show();
      } else {
        $input.removeClass("redBorder");
        $icon.removeClass("icon-warning-sign").addClass("icon-check").css("color", "green").show();
      }
    });
  });
&#13;
body {
  margin: 20px;
}
.input-container {
  width: 250px;
  position: relative;
}
.my-input {
  width: 100%;
}
.my-icon {
  position: absolute;
  right: 0px;
  color: red;
  top: 8px;
  display: none;
}
.redBorder {
  border: 1px solid red !important;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@*" data-semver="2.0.3" src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script data-require="bootstrap@*" data-semver="3.0.0-rc1" src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet" />
  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body style="margin-top:55px;">

  <!-- validation check -->
  <div id="header" style="margin-bottom:20px;">
    <div id="validate-click"><a href="#">Enter Below</a>
    </div>
  </div>

  <!-- input contianre -->
  <div class="form-group input-container">
    <input type="text" class="my-input" placeholder="Enter here">
    <i class="icon-warning-sign my-icon"></i>
  </div>

  <div class="form-group input-container">
    <input type="text" class="my-input" placeholder="Enter here">
    <i class="icon-warning-sign my-icon"></i>
  </div>

</html>
&#13;
&#13;
&#13;