gpt4 book ai didi

javascript - 如何以 Angular 形式实现条件要求的验证?

转载 作者:行者123 更新时间:2023-12-04 09:32:33 24 4
gpt4 key购买 nike

如果两个字段都没有输入,则两者都可以是可选的。如果名字有输入,则根据需要设置姓氏。如果姓有输入但名字没有输入,则将名字设置为 需要 .
如果一个字段有值而另一个没有,则根据需要设置其他字段。谢谢你。
所以就像我是用户并且有两个字段是名字和姓氏。如果我在名字上输入数据但姓氏为空,则根据需要设置姓氏(反之亦然)。任何的想法 ?谢谢
HTML

<div fxLayout="row" fxLayoutGap="24px" formGroupName="person">
<div fxFlex fxLayout="row">
<mat-form-field appearance="outline" class="pr-4" fxFlex>
<mat-label>Firsname</mat-label>
<input matInput #firstname formControlName="firstname" trim required/>
<button type="button" mat-button *ngIf="firstname.value" matSuffix mat-icon-button aria-label="Clear"
(click)="clearFieldFirstname()">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
</div>
<div fxFlex fxLayout="row">
<mat-form-field appearance="outline" class="pr-4" fxFlex>
<mat-label>Lastname</mat-label>
<input matInput #lastname formControlName="lastname" trim required/>
<button type="button" mat-button *ngIf="lastname.value" matSuffix mat-icon-button aria-label="Clear"
(click)="clearFieldLastname()">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
</div>
</div>
TS 代码
const personGroup = this.formBuilder.group({
firstName: [person.firstName, Validators.required],
lastName: [person.lastName, Validators.required],
});

const formGroup = this.formBuilder.group({
person: personGroup,
});

this.person.get("firstname").valueChanges.subscribe(value => {
const lastName = this.person.get("lastname");
lastName.clearValidators();
if (value && !lastName.value) {
lastName.setValidators(Validators.required);
}
lastName.updateValueAndValidity({
emitEvent: false
});
});

this.person.get("lastname").valueChanges.subscribe(value => {
const firstName = this.person.get("firstname");
if (value && !firstName.value) {
firstName.setValidators(Validators.required);
} else {
firstName.clearValidators();
}
firstName.updateValueAndValidity({
emitEvent: false
});
});

最佳答案

const personGroup = this.formBuilder.group({
firstName: [
person.firstName,
(control: AbstractControl): ValidationErrors | null => {
// do your validation logic here:
if (this.formGroup?.get('lastName').value) {
if (!control.value) {
return {required: true};
}
}
// all is fine:
return null;
}
],
lastName: [
person.lastName,
(control: AbstractControl): ValidationErrors | null => {
if (this.formGroup?.get('firstName').value) {
if (!control.value) {
return {required: true};
}
}
return null;
}
],
});

关于javascript - 如何以 Angular 形式实现条件要求的验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62769015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com