代码之家  ›  专栏  ›  技术社区  ›  uhidga

在数字验证中添加两个错误

  •  0
  • uhidga  · 技术社区  · 3 年前

    我正在使用 input type=number 并对其进行验证。
    我想做的事情:

    • 如果值不是数字-显示错误 only numbers allowed
    • 如果输入为空-显示错误 value is required

    yup.object().shape({ fieldName: yup.number().typeError("only numbers allowed").required("value required").min(0) })
    但它总是只返回typeerror

    2 回复  |  直到 3 年前
        1
  •  0
  •   Phil joseph    3 年前

    您正在尝试验证一个输入字段或type=number,如果传递了一个空字符串,则必然会产生错误。Yup验证正在积极检查该值是否是有效的JavaScript数字,并且空值或非数字字符串不符合此标准。

    1. 使用yup.mixed()允许数字和空值
    2. 使用测试方法定义自定义验证规则

    这是修改后的代码:

    
    import * as yup from 'yup';
    
    const schema = yup.object().shape({
      fieldName: yup
        .mixed() // Use mixed() to allow both numbers and empty values
        .test('is-number-or-empty', 'Only numbers allowed or value is required', (value) => {
          // Check if the value is a number or empty
          if (!value || !isNaN(value)) {
            return true; // Validation passed
          } else {
            return false; // Validation failed
          }
        })
        .typeError('Only numbers allowed'), // Type error message
    });
    
        2
  •  0
  •   Hilal Ahmad    3 年前

    function validateNumber(input) {
      if (input === "") {
        return "Error: Input cannot be empty.";
      }
    
      if (!/^\d+$/.test(input)) {
        return "Error: Input must contain only numeric characters.";
      }
    
      return "Success: Input is a valid number.";
    }
    
    // Example usage:
    const userInput = prompt("Enter a number:");
    const validationResult = validateNumber(userInput);
    
    console.log(validationResult);
    推荐文章