Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 form, disabled field is always valid

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.

like image 355
Ariel Weinberger Avatar asked Oct 20 '17 09:10

Ariel Weinberger


1 Answers

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?

like image 137
Dennis Avatar answered Oct 19 '22 22:10

Dennis