Validator

by mickeyvip

HTML

<input id="testInput" />
<button id="testButton">Test</button>
<p>Is Valid:</p>
<p id="testResult"></p>

CSS

#testInput {
    width: 250px;
}
#testResult {
    border: 1px solid gray;
    min-height: 25px;
}

JavaScript

var $testInput = $("#testInput");
var $testButton = $("#testButton");
var $testResult = $("#testResult");

var Validator = (function () {

    function Validator(lengthValidator, regularValidators, specialCharactersValidators) {
        this.lengthValidator = lengthValidator;    // this one is not used when replacing with "", bacause it matches all and will leave the string as "" after a first run
        this.regularValidators = regularValidators || []; // those will be ran for replacing them with ""
        this.specialCharactersValidators = specialCharactersValidators || []; // those are for special characters which can be present
    }
    Validator.prototype.validate = function (str) {
        var i;
        // validate length
        var isValid = this.lengthValidator.test(str);
    
        // validate all the regular rules
        for (i = 0; i < this.regularValidators.length; i++) {
            isValid = isValid && this.regularValidators[i].test(str)
        }
        if (isValid) {
            var invStr = str;
            console.log("invStr", invStr);
            // replace matches of regular rules with ""
            for (i = 0; i < this.regularValidators.length; i++) {
                invStr = invStr.replace(this.regularValidators[i], "")
                console.log(i, invStr);
            }
            // replace allowed special characters with ""
            for (var i = 0; i < this.specialCharactersValidators.length; i++) {
                invStr = invStr.replace(this.specialCharactersValidators[i], "");
            }
            console.log(i, invStr);
            // if all the rules were satisfied - the result string should be ""
            isValid = invStr.length === 0;
        }
        return isValid;
    }
    return Validator;
}

)();

var validator = new Validator(
    /.{8,20}/,
    [/[A-Z]+/g, /[a-z]+/g, /\d+/g],
    [/[!@#\$\^\*\?_~£\(\)]/g]
);
$testButton.on("click", function () {
    var str = $testInput.val();
    var isValid =...