import { AbstractControl } from '@angular/forms';
export function TrimRequiredValidator(control: AbstractControl): { [key: string]: any } | null {
const value = control.value;
if (! value) { return { appTrimRequiredValidator: { valid: false }}; }
const trimText = String(value) ? String(value).trim() : '';
return (trimText.length === 0) ? { appTrimRequiredValidator: { valid: false } } : null;
}
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<div class="form-group">
<label for="smallName">姓名 - appTrimRequiredValidator</label>
<input id="smallName" class="form-control" formControlName="smallName">
<div *ngIf="smallName.invalid && (smallName.dirty || smallName.touched)" class="alert alert-danger">
<div *ngIf="smallName.errors.appTrimRequiredValidator">
請輸入姓名(請勿輸入空白).
</div>
</div>
</div>
</form>
import { TrimRequiredValidator } from '../../validators/trim-required-validatorr';
form = new FormGroup({
smallName: new FormControl(this.defaultName, [
TrimRequiredValidator,
]),
});
get smallName() { return this.form.get('smallName'); }
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl, AbstractControl } from '@angular/forms';
import { TrimRequiredValidator } from '../validators/trim-required-validatorr';
@Directive({
selector: '[appTrimRequiredValidator]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => TrimRequiredValidatorDirective), multi: true }
]
})
export class TrimRequiredValidatorDirective implements Validator {
validate(c: AbstractControl) {
return TrimRequiredValidator(c);
}
}
<div class="form-group col-md-6 text-left">
<label for="b">移除空白必填</label>
<input type="text" class="form-control" id="b" placeholder="b" name="b" [(ngModel)]="b"
appTrimRequiredValidator #bNg="ngModel">
<ng-container *ngIf="bNg.invalid && (bNg.dirty || bNg.touched)">
<ng-container class="text-danger" *ngIf="bNg.errors['appTrimRequiredValidator']">
<label class="text-danger">請輸入內容(不含空白)</label>
</ng-container>
</ng-container>
</div>
https://blog.kevinyang.net/2017/03/10/angular-custom-validator/