Angular响应式表单:如何设置必填校验器禁止纯空白字符串
Got it, let's fix this so your name field is both required and doesn't accept just blank spaces. Here are two solid approaches you can use:
Approach 1: Custom Validator (Most Flexible)
Creating a custom validator gives you full control over the validation logic and clearer error messaging.
First, define the validator function somewhere (like a utility file or your component):
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export function noWhitespaceOnly(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { // Trim the value first to check for all whitespace const trimmedValue = control.value?.trim(); // Return error if value is null/undefined OR trimmed value is empty return (!trimmedValue) ? { whitespace: true } : null; }; }
Then update your form group to use this validator (it replaces Validators.required since it handles both required and whitespace checks):
this.setupForm = fb.group({ "name": ['John Smith', [noWhitespaceOnly()]] });
Finally, adjust your template to show the appropriate error message:
<mat-form-field appearance="fill"> <mat-label>Name</mat-label> <input type="text" matInput formControlName="name" /> <mat-error *ngIf="name.invalid && (name.dirty || name.touched)"> A name is required and cannot be blank </mat-error> </mat-form-field>
If you want separate messages for "required" vs "whitespace" (though in this case they overlap), you can combine Validators.required with the custom validator:
this.setupForm = fb.group({ "name": ['John Smith', [Validators.required, noWhitespaceOnly()]] });
And update the template:
<mat-error *ngIf="name.invalid && (name.dirty || name.touched)"> <span *ngIf="name.errors?.['required']">A name is required</span> <span *ngIf="name.errors?.['whitespace']">Name cannot be blank</span> </mat-error>
Approach 2: Use Validators.pattern
If you prefer not to write a custom validator, you can use a regular expression with Validators.pattern to enforce at least one non-whitespace character, combined with Validators.required:
this.setupForm = fb.group({ "name": ['John Smith', [ Validators.required, Validators.pattern(/^.*\S.*$/) // Matches any string with at least one non-whitespace character ]] });
Then update your template to handle the pattern error:
<mat-error *ngIf="name.invalid && (name.dirty || name.touched)"> <span *ngIf="name.errors?.['required']">A name is required</span> <span *ngIf="name.errors?.['pattern']">Name cannot be blank</span> </mat-error>
Pro Tip
Make sure to trigger validation appropriately (Angular defaults to blur/value changes, but you can adjust if needed). Also, adding (name.dirty || name.touched) to your *ngIf prevents showing the error immediately when the page loads.
内容的提问来源于stack exchange,提问作者Diskdrive

