3
votes

I have a simple form with several fields, a Cancel button and a Submit button. I am using Angular Material within the form for the controls. I have developed a custom validation directive which makes the form invalid if certain conditions are met. The validation makes the Submit button disable, as expected, but the Enter button on the keyboard is not disabled when the form is invalid.

I don't want the Enter button always disabled, only when the form is invalid. Can this be achieved?

My form is declared as follows:

<form class="dialog-form"
          novalidate
          #areaForm="ngForm"
          (ngSubmit)="onSubmit()">

My buttons are as follows:

<mat-dialog-actions align="end">
    <button mat-button
            [mat-dialog-close]="true"
            (click)="onCancel()">
        Cancel
    </button>

    <button mat-button
            [mat-dialog-close]="true"
            color="primary"
            type="button"
            (click)="onSubmit()"
            [disabled]="areaForm.form.invalid">
        {{data.buttonText}}
    </button>
</mat-dialog-actions>

Any guidance would be welcome. Thanks.

Edit Creating an @Input reference to the FormGroup appears to allow me to check if the form is valid before closing the mat-dialog and submitting the form:

onSubmit() {
    if (this.form.valid) {

        // Close the dialog.
        this.dialogRef.close(this.areaForCreation);
    };
};
1
Where is your directive ? On the form ? On the input fields ? - user4676340
Good question. I have the same problem with custom directives on the form or directly on the input field. Even with a built-in validation such as required with minlength="4" on an input field I have the following problem: The user can click in the field, delete the text back to less than 4 characters (at which point the Submit button visually disables) then press Enter and the form is submitted. If however the user clicks in the field, deletes back to less than 4 characters and clicks out of the field, or press Tab, then Enter does not Submit. - TDC
:D no, I mean, you said you created a directive. Where are you actually putting it ? This will shape my answer to you, so I would rather not miss the point of your question ! - user4676340
Some forms have a validation directive applied at Form level, if they need to determine the form's validity using several fields. Some forms have a directive applied at Input level if I only need to determine the validity of the value entered in the field. It appears the problem though is not related to any validator, but to the Enter key submitting the form even if the form is invalid. - TDC
Again, I don't care about that, I want to know what you used. If you're looking for a solution, I can give you a very easy one, but the way you wrote that, you are actually facing an issue, do I need to know what you did to lead you the right way. - user4676340

1 Answers

3
votes

It should be areaForm.invalid not areaForm.form.invalid