My form is made in the following way:
<form #form="ngForm" novalidate (ngSubmit)="register(form);">
<div class="registerinput">
<label for="firstname">First Name</label>
<input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
<div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.required" class="alert-danger">
Please enter your name
</div>
<div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.maxlength" class="alert-danger">
Max length is 30 characters
</div>
<div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.pattern" class="alert-danger">
Only letters are allowed
</div>
</div>
<div class="registerinput">
<button type="submit" class="btn-register">Register</button>
</div>
</form>
I'm getting the following error:
EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
It seems like it cannot find my controls. However, when I try to print out form.controls, I get the following result:
So in this case, it finds them just fine. What is the problem here? I've made something similar in the past that worked.
UPDATE: I found out that instead of for example form.controls.firstname.touched
, I have to access them using just firstname.touched
. I just don't understand why, because I have another file in the same project where I'm using forms which has been made in the exact same way, but in that one I was using form.controls.*
. I guess you can use firstname.touched
if you have declared a template reference variable, but I don't know under which circumstances you can use form.controls.*
.
Another way of doing validation is :
<form #form="ngForm" novalidate (ngSubmit)="register(form);">
<div class="registerinput">
<label for="firstname">First Name</label>
<input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
<div [hidden]="!firstname.touched && !firstname.errors?.required" class="alert-danger">
Please enter your name
</div>
<div [hidden]="!firstname.touched && !firstname.errors?.maxlength" class="alert-danger">
Max length is 30 characters
</div>
<div [hidden]="!firstname.touched && !firstname.errors?.pattern" class="alert-danger">
Only letters are allowed
</div>
</div>
<div class="registerinput">
<button type="submit" class="btn-register" [disabled]='!form.valid'>Register</button>
</div>
</form>
This one is pretty simple and easy way of doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With