Angular 4 form, disabled field is always valid
Asked Answered
E

1

5

Might seem like an odd form, but I simplified it for the sake of the question here, and that's not my actual form. But the same scenario happens here.

<form (ngSubmit)="submit(form)" #form="ngForm">
    <div>
        Full name:
        <input name="fullName" required>
    </div>
    <div>
        Would you like to receive birthday gifts from us?
        <input type="checkbox" name="gifts" [(ngModel)]="isAddressEditable">
    </div>
    <div>
        Gift shipping address:
        <input name="giftAddress" required [disabled]="!isAddressEditable"> // false (disabled) by default
    </div>

    <button type="submit" [disabled]="form.invalid">Register now!</button>
</form>

So we have a template-driven form with three fields. The "Register now!" button will be disabled as long as the form is invalid.

The problem is that as long as the "Gift shipping address" field is disabled, it doesn't count in form validation and it's enough to fill in the full name to make the form valid.

As soon as I tick the checkbox ("Would you like to receive birthday gifts from us?"), the input is not disabled anymore, and therefore validation applies.

I'm not sure if this is the designed behaviour, but I was wondering if there is a way to apply validation on disabled fields as well.

Extraversion answered 20/10, 2017 at 9:31 Comment(1)
Wondering about the use case here? Why would a disabled field be included in validation? If you want validation here, why not set validation on the checkbox, which then enables the field and also fires the validation of the field?Prohibitionist
S
8

As far as I know, I had the same problem before. I fixed it by using "readonly" instead of "disabled" on the input.

<input name="giftAddress" required [readonly]="!isAddressEditable"> // false (disabled) by default

Can you try above suggestion?

Solecism answered 20/10, 2017 at 9:39 Comment(3)
Tried the above, but since I'm using Angular Material I need to use the visuals of the "disabled" field. Of course I could design something that looks similar for readonly, but I'm trying to find a clean way around it. Thank you though!Extraversion
@ArielWeinberger did you ever find a solution. Having the same problemTimorous
@ArielWeinberger same issue hereHellraiser

© 2022 - 2024 — McMap. All rights reserved.