Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
var validate = (function() {  
  //Make these variables accessible to all functions inside validator
  var inputData, againstValue, attr, attrRule;  
  //Determine which message type should be used
  var validationMessage = {
    number: {
      //Generate the message for a specific attrRule
      greaterThan: function() {
        return inputData + ' is not greater than ' + againstValue;
      }
      /*
      lessThan: function() {
        return inputData + ' is not less than ' + againstValue;
      }
      //More messages here
      */
    }
  };  
  //Validation patterns
  //Passed-in data are compared against the desired value (againstValue)
  var validationDefinitions = {
    number: {
      greaterThan: function() {
        return inputData > againstValue;
      } 
      /*
      ,lessThan: function() {
        return inputData < againstValue;
      }
      //More rules here
      */
    }  
  };
  //Run the checks against the validation patterns
  var validationCheck = function(passedCheck) {
    //Only generate a message value was not validated
    if(!passedCheck) {
      return validationMessage[attr][attrRule]();
    }
  };
  //Starts off the validation
  return function() {
    var args = arguments;
    attr = args[1];
    attrRule = args[2];
    inputData = args[0];
    againstValue = args[3]; 
    //Kicks off the validation check with supplied data
    return validationCheck(validationDefinitions[attr][attrRule]());
  };  
  
})();
//Usage: validate(inputData, 'number', 'greaterThan', 5);
alert(validate(4, 'number', 'greaterThan', 5));
//Output: '4 is not greater than 5'
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers