powmedia / backbone-forms

Form framework for BackboneJS with nested forms, editable lists and validation
MIT License
2.17k stars 415 forks source link

Validation on disabled fields. #485

Closed natkuu closed 8 years ago

natkuu commented 8 years ago

I create the form by dynamically passing the schema to it. I can disable and enable some fields in the form depending on user's selection. However, when I submit the form, the validation is triggered on the full schema and ignores disabled fields. Is there a way for the validation to ignore disabled fields?

exussum12 commented 8 years ago

Surely your validation should check for that ? When I needed to do something similar I used a custom function to check. The field has been disabled for some reason so the validation should check that reason and then if needed run the value validation.

Would that solve your issue ? Not validation a disabled form would caused some users some issues.

bryce-gibson commented 8 years ago

We decided to override the base editor validate implementation to achieve this:

validate = Backbone.Form.editors.Base::validate

Backbone.Form.editors.Base::validate = ->
  return null if @$el.prop('readonly')
  return null if @$el.prop('disabled')
  return validate.apply @, arguments

Not sure if that's something you'd want to do, but it's working for us :-)

natkuu commented 8 years ago

Thanks for your comments. To get it working I ended up overriding validate function:

validate: function() {
    var errors = false,
        fields = this.bodyView.fields;

    _.each(fields, function(field) {
        if (!field.$(':input').is(':disabled')){
            var errs = field.validate();
                if (errs) {
                    errors = true;
                }
        }
    }, this);
    if(errors) {
        return false;
    }
    return true;
}

Perhaps something like this should be added to the form? It seems obvious that disabled fields are not getting validated ;-)

exussum12 commented 8 years ago

@glenpike whats your opinion ? I would argue that is correct now, The validation should leave your model in a consistent state, if this is added a disabled field is updated without being validated

bryce-gibson commented 8 years ago

FWIW, I think it's correct currently -- the validation should apply to disabled/readonly fields.

It's also simple enough to override if desired.

ps, that override we use is just the following in javascript (for anyone who doesn't coffeescript :-) ):

const validate = Backbone.Form.editors.Base.prototype.validate

Backbone.Form.editors.Base.prototype.validate = function validate() {
  if (this.$el.prop('readonly') || this.$el.prop('disabled')) {
    return null
  }
  return validate.apply(this, arguments)
}

(By returning null, we basically just pretend the field is valid if either of the attributes are present)

glenpike commented 8 years ago

Yes, I think I'm happy with the workaround here. We have something similar, but maybe not as clean.