xtreamsrl / ngx-validation-errors

Angular library to easily show input validation errors
MIT License
38 stars 11 forks source link

Validation on disabled fields that become enabled #21

Open psenechal opened 4 years ago

psenechal commented 4 years ago

Hey Luca,

I have a bit of an edge case here and I'm not sure if there's anything that can be done to address it. I have a form that has a field that is required. However, that field is disabled until a value from another field is selected, then it is enabled.

If I choose a value for the other field first and the disabled field is enabled, the validation works fine.

If I try to submit the form and the validation runs before that field can be enabled, I get the following error in the console and validation will not work for the field that was disabled...even after eventually being enabled:

Cannot convert undefined or null to object

It's perfectly understandable why it's doing this...technically a disabled form field is ignored, even when the form values are submitted. The problem is that directives cannot be assigned conditionally. So I cannot only apply the validation directive when the field is enabled.

The only work-around I have come up with is creating a dummy field that looks disabled in addition to an enabled field and surround each one with an *ngIf depending on if the value of the other field is present. Feels like a hack to me though.

Might you have any suggestions on how to handle this? Thanks for any suggestions.

rams23 commented 4 years ago

Hi @psenechal i looked into the problem, the error is due to the errors object in the formControl that is undefined if it is disabled, but it is marked as invalid. From the functional point of view the situation is a bit tricky to handle because it depends on the specific case. I'll update the library to handle the errors object being undefined. What do you think that the behaviour should be?

psenechal commented 4 years ago

This is definitely a bit tricky. I think the behavior should be that if the ngxValidationErrorsField directive is applied (or the corresponding HTML tags surround the formControl), it shouldn't attempt to add the validation block to the formControl if it is undefined...since technically it doesn't exist at this point on the form.

I think this will work as long as after enabling the formControl, setting the validations, and attempting to run the validation on the form again, it will still add the validation block.

I wish they had something similar to getRawValues() (which returns the values of disabled fields as well), but that actually returns the formControls and not just the values. That would be useful.

Let me know if this will work. Thanks so much for the awesome support as usual.