Javascript:对象数组的数据验证



我运行这个任务是为了教我的兄弟,他被要求创建一个简单的Javascript程序来验证这些数据

[
    {code: ‘10001’, amount: ‘’},
    {code: ‘10002’, amount: ’50.00’},
    {code: ‘’, amount: ’60.00’},
    
]

我需要显示错误,如果有一个金额,代码不应该是空的。

感谢@Majed Badawi,但使用固定的验证表达式。

const data = [
  {code: '1000', amount: ''},       // is okay
  {code: '10002', amount: '50.00'}, // absolutely valid
  {code: '', amount: '60.00'},      // invalid
  {code: '', amount: ''},           // empty but still valid
];
const validFlags = data.map(e => !e.amount || e.code);
const isValid = validFlags.every(f => f);
console.log("Validation per record", validFlags.map(Boolean));
console.log("Final result", isValid);

您可以使用.some:

const data = [
  {code: '1000', amount: ''},
  {code: '10002', amount: '50.00'},
  {code: '', amount: '60.00'},   
];
const isInValid = data.some(e => e.amount && !e.code);
console.log("Data is not valid?", isInValid);

或者使用.every:

const data = [
  {code: '1000', amount: ''},
  {code: '10002', amount: '50.00'},
  {code: '', amount: '60.00'},   
];
const isValid = data.every(e => !e.amount || e.code);
console.log("Data is valid?", isValid);

我的意思是,如果你总是得到一个objs数组,为什么不使用Joi您可以定义您的模式,并在它们的对象上设置每个道具的特征或需求https://joi.dev/api/?v=17.3.0

相关内容

  • 没有找到相关文章

最新更新