skip to Main Content

I am using simple code to validate whether input box is empty or not and just showing check icon and warning icon accordingly.

enter image description here

You can see working PLUNKER here.

Problem: This set of code works fine for one set of Label:Input Box.

Imagine if we have number of input control throughout the website.
I am looking for a solution which is quite generalized. No need to repeat same set of HTML, CSS or JS code over and over again.
I know its hard to avoid some duplication but wanna write less repetitive code.

// 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>

Note: Please don’t refer any third party control.

5

Answers


  1. // 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>

    You can try like this

    Login or Signup to reply.
  2. Make it a jQuery plugin: https://jsfiddle.net/1nxtt0Lk/
    I added the attribute data-validate to your <input />s so I can call the plugin on them using $('[data-validate']).

    Code:

    ;( 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();
    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;
      }
    <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>

    PS: I used the plugin boilerplate as a base script: https://github.com/jquery-boilerplate/jquery-boilerplate ;
    a commented version can be found here https://raw.githubusercontent.com/jquery-boilerplate/jquery-boilerplate/master/dist/jquery.boilerplate.js

    Other answer suggest to use a class selector to iterate over each of them. Although that solution definitely would work, I suggest to get used to write jQuery plugins as in the long term it makes your project much more clean and easy to read.

    Login or Signup to reply.
  3. You can use the classes my-input and my-icon instead of the ids.

    Inside the keyup listener you can use $(this) to refer to my-input and $(this).next() to refer to my-icon as the icon is the adjacent sibling of the input.

    Also chain your functions like this for brevity:

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

    See demo below:

    // 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();
        }
      });
    });
    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" />
    </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>
    Login or Signup to reply.
  4. You can use class selector instead id for the input. And use an data attribute to select the good icon.

    live demo

    You can see an example below :

      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>
    
    Login or Signup to reply.
  5. $(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();
          }
        });
      });
    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;
    }
    <!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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search