我有一个简单的表单,需要对用户输入进行验证。如果输入太长,我想显示一个错误:“输入的值太长了。最大值是{{ Max }}”。如何将最大值传递给dictionary.js文件中的错误字符串?此文件包含窗体中使用的所有字符串。
在validator.js文件中,我循环具有值的文本字段,如果超过最大值,则将错误消息收集到数组中。然后,错误消息显示在特定字段下面。
下面的解决方案不起作用,它在文本字段下面显示了一个文本" object“。有什么想法吗?
dictionary.js
const eng = Object.freeze({
errors: {
invalidLength: 'Entered value is too long. Max value is {{max}}.',
required: 'Mandatory info is missing'
},
...
...validator.js
const validate = (values) => {
const errors = {};
values.forEach(key => {
const value = key.value;
const max = key.max;
if (value.length > max) {
errors[key.field] = ('errors.invalidLength', {max});
}
}
});
return errors;
}发布于 2022-08-30 08:28:29
您可以将错误对象转换为以下内容:
dictionary.js
const eng = Object.freeze({
errors: {
invalidLength: (maxValue) => `Entered value is too long. Max value is ${maxValue}.`,
required: 'Mandatory info is missing'
}
}) 然后在您的验证器中: validator.js
if (value.length > max) {
errors[key.field] = eng.errors.invalidLength(max);
}发布于 2022-08-30 08:55:57
您可以尝试更新
const eng = Object.freeze({
errors: {
invalidLength: 'Entered value is too long. Max value is {{max}}.',
required: 'Mandatory info is missing'
}至
const eng = Object.freeze({
errors: {
invalidLength: `Entered value is too long. Max value is ${max}.`,
required: 'Mandatory info is missing'
}和,
if (value.length > max) {
errors[key.field] = ('errors.invalidLength', {max});
}至
if (value.length > max) {
errors[key.field] = eng.errors.invalidLength;
}https://stackoverflow.com/questions/73538891
复制相似问题