gpt4 book ai didi

Angular Form Validations - 值必须与初始值不同

转载 作者:行者123 更新时间:2023-12-01 22:15:00 25 4
gpt4 key购买 nike

我的响应式(Reactive)表单验证设置如下:

  ngOnInit(): void {
this.userForm = this.formBuilder.group({
status: {checked: this.selectedUser.status == 1},
username: [this.selectedUser.username, [Validators.required, Validators.minLength(LlqaConstants.USERNAME_MIN_LENGTH)]],
realname: [this.selectedUser.realname, [Validators.required, Validators.minLength(LlqaConstants.REALNAME_MIN_LENGTH)]],
password: ['', this.selectedUser.passhash.length > 0 ? [Validators.required, Validators.minLength(LlqaConstants.PASSWORD_MIN_LENGTH)] : null],
usercomment: [this.selectedUser.comment]
});
}

我想启用提交按钮,只要一个输入值不再等于初始值。我能找到的最简单的方法是:

disableSaveButton(): boolean {
return !this.userform.dirty || this.userForm.invalid;
}

我的问题是 dirty 属性,只要我输入一些东西,dirty 就是真的,如果我输入与初始值相同的值也是如此。我想要一个属性,告诉我 one 输入值是否不等于初始值。这是开箱即用的,还是我必须检查每个 userForm.value 是否等于 this.selectedUser.someValue

最佳答案

我创建了一个自定义验证器来解决这个问题。

验证器:

export function oneValueHasToBeChangedValidator(values: { controlName: string, initialValue: string | number | boolean }[]): ValidatorFn {
return (form: FormControl): { [key: string]: any } => {
let sameValues = true;

for (let comparingValues of values) {
if (form.value[comparingValues.controlName] != comparingValues.initialValue) {
sameValues = false;
break;
}
}

return sameValues ? {'sameValues': {values: values}} : null;
};
}

我是如何使用它的:

this.userForm = this.formBuilder.group({
status: this.selectedUser.status == 1,
username: [this.selectedUser.username, [Validators.required, Validators.minLength(LlqaConstants.USERNAME_MIN_LENGTH)]],
realname: [this.selectedUser.realname, [Validators.required, Validators.minLength(LlqaConstants.REALNAME_MIN_LENGTH)]],
password: ['', [Validators.minLength(LlqaConstants.PASSWORD_MIN_LENGTH)]],
usercomment: this.selectedUser.comment == null ? "" : this.selectedUser.comment
});

this.userForm.setValidators(oneValueHasToBeChangedValidator([{
controlName: "status",
initialValue: this.selectedUser.status == 1
}, {
controlName: "username",
initialValue: this.selectedUser.username
}, {
controlName: "realname",
initialValue: this.selectedUser.realname
}, {
controlName: "password",
initialValue: ""
}, {
controlName: "usercomment",
initialValue: this.selectedUser.comment == null ? "" : this.selectedUser.comment
}]));
this.userForm.updateValueAndValidity();

关于Angular Form Validations - 值必须与初始值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46667375/

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