在Angular 4应用程序中,如何验证表单的两个字段进行比较?
例如,假设我的表单有一个startDate和一个endDate日期字段,我想确保endDate必须大于startDate.
在我的 Angular 5 应用程序中,我想覆盖一些表单输入的默认验证行为。特别是,我想在用户插入内容后立即触发字段验证。
当前默认行为如下。例如,假设您有一个仅允许整数的验证器。
最初该字段是原始且空的:
然后用户聚焦输入并输入一些数据:
尽管插入的值无效(因为它不是整数),但尚未触发验证。它会在用户离开焦点时立即触发(例如按下 TAB 或聚焦另一个输入):
从现在开始,每次更改都会触发验证。
因此,如果用户现在返回该字段并插入一个有效值,验证器将立即完成其工作:
我想要的是让验证器在插入一些无效数据后立即将字段标记为无效,即使用户第一次插入数据并且从未离开过该字段。
forms angular-validation angular angular-reactive-forms angular-forms
如何清除表单控件上的错误。我有一种方法试图清除表单控件上的错误,但徒劳无功。
this.form.controls[ 'postalCode' ].setErrors(null);
表单控件名称是 postalCode,当我将错误设置为 null 时,它不会从该控件中删除错误。
我正在尝试为日期输入创建一个验证器。
所以我已经写了这段代码,但是没有按预期工作!
export class CustomValidators {
static dateMinimum(date: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value == null) {
return null;
}
const controlDate = moment(control.value, FORMAT_DATE);
if (!controlDate.isValid()) {
return null;
}
const validationDate = moment(date);
return controlDate.isAfter(validationDate) ? null : {
'date-minimum': {
'date-minimum': validationDate.format(FORMAT_DATE),
'actual': controlDate.format(FORMAT_DATE)
}
};
};
}
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
ERROR Error: Expected validator to return Promise or Observable.at toObservable (forms.js:749)
Run Code Online (Sandbox Code Playgroud)
我真的不知道哪件事是不正确的...我发现了很多示例,这些示例如何创建不带参数但不带参数的自定义验证器...
我需要像这样使用验证器:
this.projectForm = this.builder.group({
date: ['', Validators.required, CustomValidators.dateMinimum('2018-12-12')], …Run Code Online (Sandbox Code Playgroud) 我对读取/编辑例程使用相同的组件。async-validator与新条目完美配合。如果用户不小心更改了值并尝试恢复到保存的值,问题就会开始。我当前的代码将无论如何运行并返回现有值。我想传递更多数据以及控制值,以便我可以验证该对值是否已经存在。
我正在发布相关代码,
这是我的form control,
patientEmail: new FormControl(
null,
[Validators.email, Validators.required],
FormControlValidator.createEmailAsyncValidator(
this.asyncValidatorService
),
),
Run Code Online (Sandbox Code Playgroud)
我的异步验证器创建者类是,
export class FormControlValidator {
static createEmailAsyncValidator(asyncValidatorService: AsyncValidationService) {
return (control: AbstractControl) => {
if (!control.pristine) {
control.markAsPristine();
return asyncValidatorService
.validateEmailNotTaken(control)
.map((response: HttpResponse<boolean>) => {
return !response.body ? null : { taken: true };
});
}
return Observable.of(null);
};
}
Run Code Online (Sandbox Code Playgroud)
最后是我的服务,
@Injectable()
export class AsyncValidationService {
constructor(private httpService: HttpClientService) {}
public validateEmailNotTaken(control: AbstractControl) {
return this.httpService.getRequest(
'PatientsRegistration/IsPatientEmailExist?email=' + control.value,
);
} …Run Code Online (Sandbox Code Playgroud) 我有一个工作异步验证器,它向服务器发出 HTTP 请求以检查用户名是否已被占用。因为我不想在每次击键后调用 API,所以我需要对输入流进行去抖动。
我第一次参加throttleTime了这项服务,但是关于 SO 的另一个主题说这必须是订阅者,但还没有运气!
我的组件:
this.form = this._fb.group(
{
username: ['', [Validators.required, Validators.maxLength(50), NoWhitespaceValidator], [IsUserIdFreeValidator.createValidator(this._managementService)]]
});
Run Code Online (Sandbox Code Playgroud)
我的验证器:
export class IsUserIdFreeValidator {
static createValidator(_managementService: ManagementService) {
return (control: AbstractControl) => {
return _managementService.isUserIdFree(control.value)
.pipe(
throttleTime(5000),
(map(
(result: boolean) => result === false ? { isUserIdFree: true } : null))
);
};
}
}
Run Code Online (Sandbox Code Playgroud)
我的服务:
public isUserIdFree(userId: string): Observable<{} | boolean | HttpError> {
const updateUserCheck: UpdateUserCheck = new UpdateUserCheck();
updateUserCheck.userID = userId;
return this._httpClient.post<boolean>('UserManagementUser/IsUserIdFree', updateUserCheck));
}
Run Code Online (Sandbox Code Playgroud) 如何根据另一个字段的值有条件地验证一个字段?这是我尝试过的,但似乎不起作用
this.PDform = _formbuilder.group({
[...]
'intlNumber': ['',this.nationality == 'Abroad' ? Validators.compose([Validators.pattern(this.phoneNumberExp), Validators.maxLength(14), Validators.minLength(11), Validators.required]) : Validators ]
[...]
})
Run Code Online (Sandbox Code Playgroud) angular-validation angular angular-reactive-forms angular-forms angular5
我正在使用 angular 7 并且我有一个包含两个输入字段的表单,而第一个总是需要的,只有在选中复选框时才需要第二个。
我正在尝试将 FormGroup 与自定义验证器一起使用:
<form [formGroup]="exampleForm">
<mat-form-field>
<input matInput placeholder="first" formControlName="first">
</mat-form-field>
<mat-checkbox [(ngModel)]=" checked" [ngModelOptions]="{standalone:true}">Make second input field required</mat-checkbox>
<mat-form-field>
<input matInput placeholder="second" formControlName="second">
</mat-form-field>
</form>Run Code Online (Sandbox Code Playgroud)
exampleForm: FormGroup;
checked: boolean;
ngOnInit() {
this.exampleForm = new FormGroup({
'second': new FormControl('', [this.validateIfChecked()]),
'first': new FormControl('example', [Validators.required])
});
}
validateIfChecked(): ValidatorFn {
return (control: AbstractControl): {
[key: string]: any
} | null => {
if (this.checked) {
return control.value ? null : {
'err': true
};
}
return null; …Run Code Online (Sandbox Code Playgroud)我有一个表格,其中我将 ngx-select-dropdown 与 angular7 一起使用。在我的表单中选择选项是必需的。我想在提交表单时验证它。但是我的验证方法不适用于 ngx-select-dropdown 库,并且在 ngx-select-dropdown 的文档中我找不到任何有关验证的帮助信息。是否可以验证它?
<ngx-select-dropdown (change)="onSelectDropdown($event)" name="unit" [config]="config"
[ngClass]="{ 'is-invalid': f.submitted && !unit.valid }"
[options]="unitsList"
[(ngModel)]="createUser.unit" id="unit" #unit="ngModel" required>
</ngx-select-dropdown>
<div *ngIf="f.submitted && !unit.valid" class="invalid-feedback">Unit is required</div>
Run Code Online (Sandbox Code Playgroud) 我是角度的新手。我正在尝试一些东西并被卡住了。在我的表单中,我想将服务器验证响应显示为来自 laravel rest api 的错误。但不知道如何在模板中存储和显示。我能够将它记录到控制台,但无法通过错误消息进一步移动。
回复有点像这样——
{
"message": {
"firstname":["The firstname field is required."],
"lastname":["The lastname field is required."],
"email":["The email field is required."],
"password":["The password field is required."]
}
}
Run Code Online (Sandbox Code Playgroud)
服务代码:
registerUser(user): Observable<any> {
return this.http
.post<any>(`${this.url}/register`, user)
.pipe(map(res => res.message));
}
Run Code Online (Sandbox Code Playgroud)
组件类中的注册用户方法:
registerUser() {
console.log(this.registrationForm.value);
this.authService.registerUser(this.registrationForm.value).subscribe(
res => console.log(res),
err => console.log(err)
);
}
Run Code Online (Sandbox Code Playgroud)
另外,如果我在任何地方出错,请纠正我,我应该如何纠正它
validation server-side-validation angular-validation angular