aspnet-client-validation icon indicating copy to clipboard operation
aspnet-client-validation copied to clipboard

Do not validate disabled fields

Open haacked opened this issue 1 year ago • 4 comments

Fixes #90

Note this does not handle disabled fieldsets because we just rely on the browser for that. If that assumption is incorrect, we can fix that in a subsequent PR.

haacked avatar Jan 02 '24 20:01 haacked

I noticed that when a disabled element is valid, we mark it green. We should completely ignore disabled elements. I'll dig into this a bit more.

haacked avatar Jan 05 '24 21:01 haacked

Ok, I updated the disabled fields demo to test dynamic support for fields that are enabled/disabled. Turns out the value of disabled is not in the attributes collection nor in the oldValue property of MutationRecord, so we need to do some special casing.

Note: for this demo to work, we need to be watching for DOM changes, hence:

<script>
    const service = new aspnetValidation.ValidationService(console);
    service.bootstrap({ watch: true });
</script>

You can dynamically enable/disable the two inputs and validation works correctly. For example, by default, input 1 is disabled and input 2 is enabled, so submitting the form with no values yields:

image

If I enable input 1 and then try to submit again, we see it now shows an error message.

Screenshot 2024-01-05 at 7 00 16 PM

If I disable both, the form is valid and submits successfully.

haacked avatar Jan 06 '24 03:01 haacked

We ended up not using watch: true. I think we should try to make this work as expected without.

The demo would re-validate the input in updateStatus() to handle the reset - if a form has enabled/disable behavior I don't think that's too much to ask.

I think we should have two demos. It should Just Work™️ if watch: true. Otherwise, we make the user re-validate the input if they disable/enable it.

haacked avatar Jan 08 '24 23:01 haacked

Ok, try that out and let me know what you think.

haacked avatar Jan 09 '24 00:01 haacked

@dahlbyk do you want to take another look or should I go ahead and merge?

haacked avatar Feb 06 '24 23:02 haacked

I made some changes thanks to @dahlbyk's feedback. His feedback made me realize that ignoring validation on a disabled field is orthogonal to whether we update the input's current validation state when it is enabled/disabled.

So we never validate a disabled input. We always validate an enabled input.

However, if an input is currently enabled and showing a validation error and you dynamically disable the input, the validation error will continue to be displayed. But the next time you submit the form, the field will be ignored and the validation message will be cleared.

If you want the validation message to be cleared at the time the input is disabled, there's two options:

  1. service.bootstrap({ watch: true });
  2. service.reset(input);

I've included demos of both.

haacked avatar Mar 18 '24 23:03 haacked