我有在FormBuilder的帮助下构建的Angular表单。
窗体包含一个FormArray,其中具有用户想要的多个字段。我已经为字段设置了验证器
this.fb.array([this.fb.control('', Validators.required)])
Run Code Online (Sandbox Code Playgroud)
并且对于每个新的push验证器都是相同的。
问题是我不知道如何访问特定字段的isValid属性,因为它们与FormControlvia 绑定[formControlName]="index"。
我已经尝试过这样做,但是似乎没有用
<div *ngIf="array.at(index).invalid" class="alert alert-danger p-2">
</div>
Run Code Online (Sandbox Code Playgroud)
当array是formArray.controls从父通过。
forms validation typescript angular angular2-form-validation
我正在尝试在使用Smart Admin模板(来自wrapbootstrap的主题)的angular 7应用程序上执行表单验证。
我的问题是,第一次刷新浏览器时,甚至当我导航到不包含其他表单的组件时,它都能按预期工作。当我导航到还包含带有其自身验证选项的表单的组件时,就会出现此问题。
此外,窗体的实际“有效”状态仍按预期工作。它只是不显示表单上的引导类和消息。
我尝试过重置表单,重置任何异步/非异步验证器以及其他我能想到的东西。
最后,在组件之间导航期间没有任何错误或任何错误。
这是我处理导航的主要模块(main.routing.ts):
import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from "@angular/core";
import { MainLayoutComponent } from '@app/shared/layout/app-layouts/main-layout.component';
import { MainComponent } from "./main.component";
import { SettingsComponent } from '../settings/settings.component';
import { GetAccountsComponent } from '../administration/get-accounts/get-accounts.component';
import { GetUsersComponent } from '../administration/get-users/get-users.component';
import { CreateAccountComponent } from '../administration/create-account/create-account.component';
import { CreateUserComponent } from '../administration/create-user/create-user.component';
import { GetTeamsComponent } from '../user/get-teams/get-teams.component';
import { GetGamesComponent } from '../user/get-games/get-games.component';
import { CreateTeamComponent } from …Run Code Online (Sandbox Code Playgroud) smartadmin angular angular-reactive-forms angular2-form-validation angular7
我有角形。
当我打开应用程序时,控制台会记录in fooValidation四次,而我什么也不做。
in fooValidation
in fooValidation
in fooValidation
in fooValidation
Run Code Online (Sandbox Code Playgroud)
为什么?这是设计使然吗?如何使其仅在表单提交后或焦点位于指定字段时执行?
in fooValidation
in fooValidation
in fooValidation
in fooValidation
Run Code Online (Sandbox Code Playgroud)
基本上,我有一些表单输入,它们的验证相互依赖(即,如果您在一个时间范围内,“从”时间必须小于“到”时间),但我不确定如何去做这件事。
这是我的表单组:
this.form = this.fb.group({
fromTime: ["", [Validators.required, CustomValidator.myValidationFunction(this.form.get("toTime").value)]],
toTime: ["", [Validators.required]]
});
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我的验证器:
static myValidationFunction(testing) {
const toTime = testing; // only comes here 1 time
return control => {
return toTime /*this value never changes*/ ? null : { test: {} };
};
}
Run Code Online (Sandbox Code Playgroud)
但似乎值xortoTime仅在创建验证器时才第一次设置。有没有办法将动态输入传递给自定义验证器?
我对 angular 还很陌生,但已阅读有关自定义表单验证的文档,但似乎找不到我的答案
typescript angular angular-reactive-forms angular2-form-validation
我无法找到如何使用 ng-select 中所需的选项。
我已经尝试过这个:
<ng-select
#skills
required
[ngClass]="{ 'is-invalid': f.submitted && skills.invalid }"
[items]="options"
bindLabel="label" bindValue="value"
[multiple]="true" placeholder="Select Skills"
[(ngModel)]="registerUserData.skills"
name="skills[]">
</ng-select>
<div *ngIf="f.submitted && skills.invalid" class="invalid-feedback">
<div *ngIf="skills.errors.required">
Skills are required
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
但那里没有运气..
我不清楚我应该在何时何地调用updateValueAndValidity。
假设我有一个包含许多 formControl 的 formGroup。现在,基于某些单选选项选择,会触发一个事件来修改多个 formControl 的“验证器”。
Q1:我是在修改后立即调用 updateValueAndValidity 还是在所有修改调用完成后调用 updateValueAndValidity?
Q2:我是否可以通过表单更新formGroup / formControls来更新所有formControls
this.form.updateValueAndValidity('emitEvent': false);
Run Code Online (Sandbox Code Playgroud)
或单独调用每个 formControls
this.form.get('control1').updateValueAndValidity('emitEvent': false);
this.form.get('control3').updateValueAndValidity('emitEvent': false);
this.form.get('control8').updateValueAndValidity('emitEvent': false);
Run Code Online (Sandbox Code Playgroud) 我正在使用有角4形式,我有一些领域。和first_name,last_name和company对我来说真的很重要。我想强迫用户填写这三个字段之一。我该怎么做?
这是.ts代码:
this.contactForm = this.fb.group({
first_name: [null, Validators.compose([Validators.required])],
last_name: [null, Validators.compose([Validators.required])],
email: [null, Validators.compose([this.validateEmail])],
company: [null],
position: [null],
});
Run Code Online (Sandbox Code Playgroud)
一个html:
<form [formGroup]="contactForm" fxLayout="column">
<md-input-container class="data_light">
<input class="data_font capital" mdInput placeholder="{{'Contacts.FirstName' | translate}}" [formControl]="contactForm.controls['first_name']">
</md-input-container>
<small *ngIf="contactForm.controls['first_name'].hasError('required') && contactForm.controls['first_name'].touched" class="mat-text-warn data_light">{{'Contacts.firstNameReq' | translate}}
</small>
<md-input-container class="data_light">
<input class="data_font capital" mdInput placeholder="{{'Contacts.lastName' | translate}}" [formControl]="contactForm.controls['last_name']">
</md-input-container>
<small *ngIf="contactForm.controls['last_name'].hasError('required') && contactForm.controls['last_name'].touched" class="mat-text-warn data_light">{{'Contacts.lastNameReq' | translate}}
</small>
<md-input-container class="data_light">
<input class="data_font" mdInput placeholder="{{'Contacts.email' | translate}}" [formControl]="contactForm.controls['email']"
(blur)="checkContactEmail()">
</md-input-container>
<small *ngIf="contactForm.controls['email'].hasError('validateEmail') && contactForm.controls['email'].dirty" class="mat-text-warn data_light">{{'Contacts.emailValid' …Run Code Online (Sandbox Code Playgroud) 我正在做一个项目,我想在表单数组字段上进行所需的验证。这是我的模板
<div formArrayName="price" *ngFor="let p of vehicleForm.get('prices.price').controls; let i=index">
<div class="price-form-repeater" [formGroupName]="i">
<div class="col-md-6 col-sm-12 cust-col">
<label class="col-sm-4 dark-label" for="priceType">Price Type:</label>
<div class="col-md-6" >
<select id="priceType" formControlName="type" class="form-control" data-placeholder="select" >
<option ></option><!-- Required for data-placeholder attribute to work with Chosen plugin -->
<option value="public">Public</option>
</select>
<div *ngIf="p.controls.type.errors && (p.controls['type'].dirty || p.controls['type'].touched)) ||
(p.controls['type'].untouched && formSubmitAttempt)"class="alert alert-danger">
<div [hidden]="(!p.controls['type'].errors.required)">Price type is required.</div>
</div>
</div>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这是我的组件
prices: this.fb.group({
price: this.fb.array([this.priceField()]) ,
})
priceField():FormGroup {
return this.fb.group({
type: ['',Validators.required],
vat_type: …Run Code Online (Sandbox Code Playgroud) 因此,我创建了一个自定义验证器,以验证“新密码”字段和“确认密码”字段是否匹配。在组件级别,它很棒。仅当两个输入不匹配时才会显示错误消息。
问题是,我禁用了提交按钮,直到表单有效为止,但是当我使用此自定义验证器时,整个表单永远不会通过验证。填写for表单时,所有组件验证都会通过,但表单验证不会通过。
我在这里想念什么?
定制验证器代码如下所示:
import {FormGroup, ValidationErrors, ValidatorFn} from "@angular/forms";
export const matchingInputsValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
let pass = control.get('NewPassword').value;
let confirmPass = control.get('ConfirmPassword').value;
return pass === confirmPass ? { matchingInputs: true } : { matchingInputs: false };
};
Run Code Online (Sandbox Code Playgroud)
我将自定义验证器导入我的组件,并在组件中声明我的表单控件,如下所示:
expiredPasswordForm: FormGroup;
oldPassword = new FormControl('', Validators.compose([Validators.required, Validators.minLength(4)]));
newPassword = new FormControl('', Validators.compose([Validators.required, Validators.minLength(4)]));
confirmPassword = new FormControl('', Validators.compose([Validators.required, Validators.minLength(4)]));
Run Code Online (Sandbox Code Playgroud)
在我的ngOnInit()生命周期挂钩中,我像这样创建表单组:
this.expiredPasswordForm = this.fb.group({
'OldPassword': this.oldPassword,
'NewPassword': this.newPassword,
'ConfirmPassword': this.confirmPassword
}, { validator: matchingInputsValidator}); …Run Code Online (Sandbox Code Playgroud) html javascript angular angular-reactive-forms angular2-form-validation
我写了一个自定义的表单验证器,但errors它只是有"_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": {"_isScalar": false}, "operator": {}}, "operator": {"total": 1}并且表单永远不会有效。
这是我的验证器:
export function asyncEmailValidator(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return of(control.value).pipe(
map(res => {
return res && res.indexOf('example.de') < -1 ? { eMailUnavailable: true } : null;
}),
take(1), finalize(() => {})
);
};
}
Run Code Online (Sandbox Code Playgroud)
这是我如何使用它:
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
asyncEmailValidator()
]);
Run Code Online (Sandbox Code Playgroud)
从调试中,我发现我检查 example.de 的地图块从未到达过,我不明白为什么。在显示内部返回之前使用和输出函数本身。
我在网上的多个示例中看到了这种结构,但它似乎对我不起作用。
我在用 @angular/forms 10.0.14
angular angular-reactive-forms angular-forms angular2-form-validation
angular ×10
typescript ×2
validation ×2
angular7 ×1
forms ×1
html ×1
javascript ×1
required ×1
smartadmin ×1