aurelia / validatejs

Enables expressive validation using decorators and/or a fluent API.
MIT License
22 stars 23 forks source link

How to attach custom validator rules? #38

Closed apawsey closed 8 years ago

apawsey commented 8 years ago

I've 'ported' the strong password validator from the old aurelia validation because I needed to use it, but I can't seem to find any way to attach it to the validator, or more specifically, I can't find a way to create a new ValidationRule.

import validate from 'validate.js';

validate.validators.strongPassword = function(value, options, key, attributes) {
    let threshold = 3;
    if (options.hasOwnProperty("minimumComplexityLevel")) {
        threshold = options.minimumComplexityLevel;
    }
    let errorMessage = "should contain " + (threshold < 4 ? "at least " + threshold + " of the following groups:" : "a combination of") + " lowercase letters, uppercase letters, digits or special characters"
    if (typeof (value) !== 'string') {
        return false;
    }
    let strength = 0;
    strength += /[A-Z]+/.test(newValue) ? 1 : 0;
    strength += /[a-z]+/.test(newValue) ? 1 : 0;
    strength += /[0-9]+/.test(newValue) ? 1 : 0;
    strength += /[\W]+/.test(newValue) ? 1 : 0;

    return strength >= threshold ? null : errorMessage;
}

and then later in my constructor, I'm trying to get to the equivalent of...

this.validator.config.addRule('password', new ValidationRule('strongPassword', {minimumComplexityLevel:4}));

but I can't get new ValidationRule to work. It's not exported, and webpack is getting upset with me trying more 'creative' approaches.

disclaimer: I don't claim any level of quality over this code... I haven't even had a chance to run it yet :)

plwalters commented 8 years ago

Duplicate of https://github.com/aurelia/validatejs/issues/4