I'm new in Angular. I have a form in html:
<form class="input-form" [formGroup]='terminalsForm'>
<mat-form-field class="form-full-width">
<input matInput placeholder="From" [matAutocomplete]="auto" formControlName='terminalInput' required>
</mat-form-field>
<span>Your choice is: {{terminalsForm.get('terminalInput').value | json}}</span>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let terminal of (filteredTerminals)?.results" [value]="terminal">
<span>{{ terminal.name }}, {{terminal.city}}</span>
</mat-option>
</mat-autocomplete>
</form>
It works fine and span indicate me if I selected an object or not (it returns a json with id included if I autocomplited object). How can I validate this field with select required? I need to pass terminal Id next so not selecting is supposed to be a validation error. Thanks!
Updated on 24-01-2019
As per comments from @D. Make, custom validator function is needed in the input.
So, I have updated the code on stackblitz.
I have added a new validator called forbiddenNamesValidator, which allow users to enter names only from suggested values. It's been added to myControl like below:
autocomplete-simple-example.ts
...
constructor() {
this.myControl.setValidators(forbiddenNamesValidator(this.options));
}
...
export function forbiddenNamesValidator(names: string[]): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
// below findIndex will check if control.value is equal to one of our options or not
const index = names.findIndex(name => {
return (new RegExp('\^' + name + '\$')).test(control.value);
});
return index < 0 ? { 'forbiddenNames': { value: control.value } } : null;
};
}
Ad in html, it's handled like below:
...
<mat-error *ngIf="myControl.hasError('forbiddenNames')">
You should enter value from suggested one only. <strong>'{{myControl.errors.forbiddenNames.value}}'</strong> is not allowed.
</mat-error>
...
Original Answer
To handle validation errors, you have to attach it to input[required] inside mat-form-field:
<mat-form-field class="form-full-width">
<input type="text" matInput placeholder="Terminals" formControlName="terminal" required [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let terminal of (filteredTerminals)?.results" [value]="terminal">
<span>{{ terminal.name }}, {{terminal.city}}</span>
</mat-option>
</mat-autocomplete>
</mat-form-field>
You can also check Angular Material Team's official example on stackblitz.
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