请在此处参考 stackblitz 中的项目 。
可以看出,我的反应形式的控件为firstNumber、secondNumber和thirdNumber。我需要对表单控件进行验证thirdNumber,使其值不应大于在firstNumber和之间具有最小值的表单控件的值secondNumber。
validateThirdNumber每当表单控件发生更改时,组件中的自定义验证器都可以正常工作thirdNumber,但我需要对表单控件的更改进行验证firstNumber,secondNumber因为验证逻辑也可以根据表单控件的更改
firstNumber而更改secondNumber。
为此,我添加了一个有关表单控件更改的事件firstNumber,并将secondNumber表单控件标记thirdNumber为touched但其验证似乎没有被触发。
那么,如何在表单控件thirdNumber发生变化时触发表单控件firstNumber的验证secondNumber?
另外,为什么this.myFormGroup有时在自定义验证器中未定义(请参阅登录于app.componen.ts)line:22,即使在绑定this到其表单控件声明并this.myFormGroup在 中定义后也是如此 constructor ?
当在表单组上使用带有异步验证器的反应式表单时,如果通过patchValue在构造函数或 in 中使用来更改表单组的值ngOnInit- 即使异步验证器可观察完成,表单仍保持PENDING状态。
在示例中,您会看到一个包含两个字段的简单表单,其中指示表单状态和验证器状态。在代码中,ngOnInit我调用patchValue表单,导致表单进入PENDING状态,并调用异步验证器。
异步验证器没有做太多事情,它只是等待 1 秒,然后返回一个null错误对象,基本上表明表单是有效的。您可以在指示中看到验证已完成,但表单仍保持PENDING状态。
ngOnInit如果您在构造函数或对象构造之外的任何时间触发字段值的更改,那么VALID当验证程序完成时,表单会进入状态。如果您将值更改包装在 中,这也适用setTimeout。
难道我做错了什么?这是正常行为,还是 Angular 中的错误?
如何对(Jest此处)自定义验证器进行单元测试,其中有FormGroup?我见过这个问题,但它是关于FormControl.
要测试的功能。
import { FormGroup } from '@angular/forms';
/**
* @description Validate if passwords are different.
* @function validatePasswords
* @param {string} passwordControlName - reference to formControlPassword of the contactForm.
* @param {string} confirmPasswordControlName - reference to formControlConfirmPassword of the contactForm.
* @returns {(formGroup: FormGroup) => void}
*/
export function validatePasswords(
passwordControlName: string,
confirmPasswordControlName: string
): (formGroup: FormGroup) => void {
return (formGroup: FormGroup) => {
// Get values of desired controls …Run Code Online (Sandbox Code Playgroud) unit-testing jestjs angular angular-reactive-forms angular-custom-validators
我正在尝试使用正则表达式创建仅适用于整数(例如 60)的验证器。我正在尝试这样做:
meter: ["", Validators.required, Validators.pattern(/[0-9]/)]
Run Code Online (Sandbox Code Playgroud)
它不起作用,但我不得不说我对这种技术并不熟悉。任何人都可以阐明如何修改此表达式以仅接受整数吗?这个数字是针对身高的,身高又分为米和厘米。
我已经搜索过,但我可以找到小数,所以,不知何故,也许因为它太微不足道了,对于整数,我找不到,事实上,我昨天在这里找到了,但我找不到答案了,我找到了,我在寻找另一件事。
我正在尝试将自定义验证器添加到我的 component.ts 中
自定义验证器文件:
import { FormGroup, ValidationErrors } from '@angular/forms';
export class ProfileCustomValidators {
static validateTime(fg: FormGroup): ValidationErrors {
const staffForm = fg.get('staffForm')
const fromTime = staffForm.get('fromTime').value;
const toTime = staffForm.get('toTime').value;
if(fromTime > toTime) {
return {
'endTime': {
message: 'End time should be greater than start time'
}
}
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
组件.ts
export class StaffFrom implements onInit {
staffForm: FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit() {
this.staffForm = this.fb.group({
fromTime: new FormControl(null, Validators.required),
toTime: new FormControl(null, …Run Code Online (Sandbox Code Playgroud) angular angular-reactive-forms angular7 angular-custom-validators
当我实际进行异步调用时,我的异步验证器不起作用(但当我用 模拟它时,它起作用Observable.of(result)。html看起来像这样:
<div class="form-group">
<label for="emailAddress" class="control-label">Email</label>
<input type="email"
id="emailAddress"
class="form-control"
[(ngModel)]="parent.EmailAddress"
name="emailAddress"
[ngModelOptions]="{updateOn: 'blur'}"
appDuplicateEmailValidator
#emailAddress = "ngModel">
</div>
Run Code Online (Sandbox Code Playgroud)
有问题的验证器是appDuplicateEmailValidator.
验证代码如下所示:
public validate(control: AbstractControl): Observable<ValidationErrors | null> {
// return observableOf({ 'isDuplicateEmail': true });
return this.checkForDupeUserAndGetValidationState(emailAddress);
}
private checkForDupeUserAndGetValidationState(emailAddress): Observable<ValidationErrors | null> {
const validationStateObs: Observable<ValidationErrors | null> = new Observable(observer => {
this.adminService.getUser(emailAddress).subscribe(
(res: any) => {
const validationState = !!res ? observableOf({ 'isDuplicateEmail': true }) : null;
console.log('Observer next, validation state: …Run Code Online (Sandbox Code Playgroud) 我不确定为什么 setValidators 在我下面的代码中不起作用。我不确定问题是什么,因为当我根据需要设置 formControl 时它没有任何影响。我想要实现的是在选择特定选项时动态设置一些所需的 FormControl。如果你有任何想法那将是惊人的。谢谢!
这是我的 HTML
<form [formGroup]="measurementsForm">
<ion-grid>
<ion-row>
<ion-col>
<ion-row class="quiz-choices">
<ion-col>
<ion-select
[interfaceOptions]="customInterfaceOptions"
formControlName="weightMeasurement"
interface="action-sheet"
placeholder="weight">
<ion-select-option value="kg">kg</ion-select-option>
<ion-select-option value="lbs">lbs</ion-select-option>
</ion-select>
</ion-col>
<ion-col>
<ion-input
inputmode="numeric"
formControlName="weightAmount"
placeholder="Weight"
value="amount">
</ion-input>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-select
[interfaceOptions]="customInterfaceOptions"
formControlName="heightMeasurement"
interface="action-sheet"
placeholder="height"
(ionChange)="onSelectFootMeasurement($event)">
<ion-select-option value="cm">cm</ion-select-option>
<ion-select-option value="ft">ft</ion-select-option>
</ion-select>
</ion-col>
<ion-col *ngIf="!showFtInput">
<ion-input
inputmode="numeric"
formControlName="heightAmountCm"
placeholder="amount">
</ion-input>
</ion-col>
<ion-col *ngIf="showFtInput">
<ion-input
formControlName="heightAmountFoot"
placeholder="foot"
inputmode="numeric">
</ion-input>
</ion-col>
<ion-col *ngIf="showFtInput">
<ion-input
formControlName="heightAmountInch"
placeholder="inch"
inputmode="numeric">
</ion-input>
</ion-col>
</ion-row>
</ion-col>
</ion-row>
</ion-grid>
</form>
Run Code Online (Sandbox Code Playgroud)
这是我的 …
html javascript ionic-framework angular angular-custom-validators
angular ×7
angular7 ×1
formbuilder ×1
html ×1
javascript ×1
jestjs ×1
observable ×1
regex ×1
unit-testing ×1