简体   繁体   中英

One rule to validate several inputs with Backbone.validation

I have 10 inputs for instance. And I want to check if they're empty using one rule but avoiding reiteration like this:

firstInput :{
    required: true,
    msg: 'Empty!'
},
// ...

tenthInput :{
    required: true,
    msg: 'Empty!'
}

Is there any method to use one rule for all inputs using Backbone Validation ? And each input can have other unique validation rules the same time, eg:

firstInput :{
    pattern: email,
    msg: 'Email!!!'
}

From the Backbone Validation documentation :

 // validation attribute can also be defined as a function returning a hash var SomeModel = Backbone.Model.extend({ validation: function() { return { name: { required: true } } } }); 

You could then adjust your model to have a function:

var SomeModel = Backbone.Model.extend({
    /**
     * List of field which are required.
     * @type {Array|Function}
     */
    required: ['firstInput', 'secondInput', /*...*/ 'tenthInput'],
    /**
     * Same format as Backbone Validation
     * @type {Object|Function}
     */
    specificValidation: {
        firstInput: {
            pattern: "email",
            msg: 'Email!!!'
        }
    },

    validation: function() {
        var inputs = _.result(this, 'required'),
            rules = _.result(this, 'specificValidation'),
            requiredRule = { required: true, msg: 'Empty!' };

        // apply the default validation to each listed field
        // only if not already defined.
        _.each(inputs, function(field) {
            rules[field] = _.defaults({}, rules[field], requiredRule);
        });

        return rules;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM