backbone-validator icon indicating copy to clipboard operation
backbone-validator copied to clipboard

Numeric min / max

Open bazineta opened this issue 11 years ago • 0 comments

I find the following to be quite helpful, as many of my models require validation of numbers (note, not strings that contain numbers, rather, actual numbers, where for example, a value must be no less than 0 and no more than 100).

I'm curious if this would be more widely useful, and if so, if a PR would be welcomed for it. Thanks. Great library!

// Add min and max number validators to Backbone Validator

function validNumber (value, expectation, valid) {
    return _.isFinite(value) ? valid(value, expectation) : 'Value not a number';
}

Validator.add('min', function (value, expectation) {
    return validNumber(value, expectation, function (value, expectation) {
        return (value >= expectation) || 'Value below minimum';
    });
});

Validator.add('max', function (value, expectation) {
     return validNumber(value, expectation, function (value, expectation) {
        return (value <= expectation) || 'Value above maximum';
    });
});

bazineta avatar Oct 02 '14 20:10 bazineta