不允许重复值的字段数组验证

Field array validation for not allowing duplicate values

我已经使用 redux 形式实现了一个字段数组组件。在我的字段数组中,我有一些验证,例如我的输入中不包含字母。我的验证函数是这样的:

const validateFieldArray = (values) => {
  const errors = {
    [LEGO_AMKA_ARRAY]: []
  };
  if (values.get(LEGO_AMKA_ARRAY)) {
    const amkas = values.get(LEGO_AMKA_ARRAY);
    amkas.forEach((field, index) => {
      const amkasErrors = {};
      const amkaField = field.get(AMKA_FIELD);
      if (!amkaField) {
        amkasErrors[AMKA_FIELD] = 'error.required';
        errors[LEGO_AMKA_ARRAY][index] = amkasErrors;
      } else if (onlyNumeric(amkaField) !== undefined) {
        amkasErrors[AMKA_FIELD] = 'error.numbers.allowed';
        errors[LEGO_AMKA_ARRAY][index] = amkasErrors;
      }
    });
  }
  return errors;
};

我想添加一个不允许重复条目的验证。如果我输入一个在前一个字段中输入的值,我一定不允许这样做。我该怎么做?

谢谢!

您可以使用 reduce 创建每个值及其在值数组中出现的字典(注意 - 您可能需要在 reduce 之前使用 map,我不确定您的数组结构是什么样的)

const dictOccurrences = values.get(LEGO_AMKA_ARRAY).reduce((acc, curr) => ({
    ...acc,
    [curr]: acc[curr] ? acc[curr] + 1 : 1,
}), {});

然后在你的代码中:

const validateFieldArray = (values) => {
  const errors = {
    [LEGO_AMKA_ARRAY]: []
  };
  if (values.get(LEGO_AMKA_ARRAY)) {
    const amkas = values.get(LEGO_AMKA_ARRAY);
    const dictOccurrences = amkas.reduce((acc, curr) => ({
    ...acc,
    [curr]: acc[curr] ? acc[curr] + 1 : 1,
}), {});
    amkas.forEach((field, index) => {
      const amkasErrors = {};
      const amkaField = field.get(AMKA_FIELD);
      if (!amkaField) {
        amkasErrors[AMKA_FIELD] = 'error.required';
        errors[LEGO_AMKA_ARRAY][index] = amkasErrors;
      } else if (onlyNumeric(amkaField) !== undefined) {
        amkasErrors[AMKA_FIELD] = 'error.numbers.allowed';
      }
      if (dictOccurrences[amkaField] > 1) {
        amkasErrors[AMKA_FIELD] = 'error.duplicate';
      }
      errors[LEGO_AMKA_ARRAY][index] = amkasErrors;
    });
  }
  return errors;
};