I am trying to check user's input of subject is an empty or exceed max character. If user not which should display: Required Information message. If user enter over 5 character and it should display Exceed Maximum Character. I do not know why no exceed max character message display if user enter more than 5 characters right away on the code.
Here is HTML file
<form class="add-form"
[formGroup]="addForm"
novalidate>
<div class="add-form__group">
<label for="subject"
class="add-form__label">
Subject
</label>
<input class="add--form__input"
[class.add-form__input--error]="(hasError('subject') || hasError('subject', 'maxlength'))"
formControlName="subject"
id="subject"
name="subject"
type="text"
placeholder="Enter a Subject Line"/>
<ng-container *ngIf="(hasError('subject') || hasError('subject', 'maxlength'))">
<p class="add-form__error-label"
*ngIf="addForm.get('subject').errors.required">
Required Information
</p>
<p class="add-form__error-label"
*ngIf="addForm.get('subject').errors.maxlength">
Exceeds Maximum Character
</p>
</ng-container>
</div>
</form>
TS file
export class AddFormComponent implements OnInit {
constructor(private fb: FormBuilder) {
/** On Init */
public ngOnInit(): void {
this.initAddForm();
}
public addForm: FormGroup;
/** Checks If Controller has Error */
public hasError(controlName: string, error: string = 'required'): boolean {
const controller: FormControl = this.addForm.get(controlName) as FormControl;
return controller.hasError(error) && controller.touched;
}
private initAddForm(): void {
this.addForm = this.fb.group({
subject: ['', [Validators.required, Validators.maxLength(5)]],
});
}
}
```````````````````````````````````````````````````````````````````
I guess its because of the below line.
Before:
public hasError(controlName: string, error: string = 'required'): boolean {
const controller: FormControl = this.addForm.get(controlName) as FormControl;
return controller.hasError(error) && controller.touched;
}
In this code, touched is changed only after tab out, as an alternative use pristine
which is updated during typing in the field itself.
public hasError(controlName: string, error: string = 'required'): boolean {
const controller: FormControl = this.addForm.get(
controlName
) as FormControl;
return controller.hasError(error) && !controller.pristine;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.