如何找到我的表单具有真实状态的“必需”错误
How to find my form has a `required` error with true state
我在 angular 中使用反应形式。我想知道我的表单是否在任何表单字段中抛出任何 required
错误。
目前我正在通过 :
找到
this.transtForm.get('Name').hasError('required')
- 但页面中存在 20 个表单字段。所以我想知道至少任何一个字段都具有真实状态的 required
错误。
我不能使用 this.transtForm.valid
- 因为用户甚至可能也输入了错误的电子邮件 ID.. 这是允许的。它将通过电子邮件模式处理重点。
这可能有帮助,像这样?
我们将 20 个字段保存在一个数组中,如下所示,一个函数将遍历该数组并在出现任何错误时发出警报。
const fields = [
{ label: 'Name', validations: ['required'] },
{ label: 'Email', validations: ['required', /\w+/g] }
];
function isValidForm() {
for (const field of fields) {
field.validations.map(validator => {
if (typeof validator === 'string') {
if (this.transtForm.get(field.label).hasError(validator)) {
alert('Your error message');
}
} else {
if (!validator.test('')) {
alert('Your error message');
}
}
});
}
}
if (isValidForm()) {
// Do stuff here...
}
我在 angular 中使用反应形式。我想知道我的表单是否在任何表单字段中抛出任何 required
错误。
目前我正在通过 :
找到this.transtForm.get('Name').hasError('required')
- 但页面中存在 20 个表单字段。所以我想知道至少任何一个字段都具有真实状态的 required
错误。
我不能使用 this.transtForm.valid
- 因为用户甚至可能也输入了错误的电子邮件 ID.. 这是允许的。它将通过电子邮件模式处理重点。
这可能有帮助,像这样? 我们将 20 个字段保存在一个数组中,如下所示,一个函数将遍历该数组并在出现任何错误时发出警报。
const fields = [
{ label: 'Name', validations: ['required'] },
{ label: 'Email', validations: ['required', /\w+/g] }
];
function isValidForm() {
for (const field of fields) {
field.validations.map(validator => {
if (typeof validator === 'string') {
if (this.transtForm.get(field.label).hasError(validator)) {
alert('Your error message');
}
} else {
if (!validator.test('')) {
alert('Your error message');
}
}
});
}
}
if (isValidForm()) {
// Do stuff here...
}