【问题标题】:Validation on auto-populated field in a form in not working - ReactJS验证表单中的自动填充字段不起作用 - ReactJS
【发布时间】:2020-04-24 14:08:54
【问题描述】:

我有一个为所有字段设置了验证的表单。对于验证,我检查每个输入值是否为required,是否具有所需的max lengthmin length。完成后,我会进行最后检查,看看整个表格是否有效。

上述验证适用于用户在输入字段中实际键入的字段(这就是我所遵循的教程所说的方法)。但是我修改了Country 输入字段和Email 输入字段,以便它们被预先填写。 Country 包含England,UK 的默认字符串,并且电子邮件字段预填充了用户从this.props.email 状态注册时填写的电子邮件。现在,如果我在预填充数据旁边的这两个字段中输入一些内容,我的表单只会返回为 valid。经过数小时的调试后,我看不出为什么...

见下面的代码:

state = {
    orderForm: {
      name: {
        elementType: "input",
        elementConfig: {
          type: "text",
          placeholder: "Your Name"
        },
        value: "",
        validation: {
          required: true 
        },
        valid: false,
        touched: false
      },
      postCode: {
        elementType: "input",
        elementConfig: {
          type: "text",
          placeholder: "PostCode"
        },
        value: "",
        validation: {
          required: true,
          minLength: 5,
          maxLength: 8
        },
        valid: false,
        touched: false
      },
      country: {
        elementType: "input",
        elementConfig: {
          type: "text",
          placeholder: "Country"
        },
        value: "England, UK",
        validation: {
          required: true
        },
        valid: false,
        touched: false
      },
      email: {
        elementType: "input",
        elementConfig: {
          type: "email",
          placeholder: "Your E-Mail"
        },
        value: this.props.email,
        validation: {
          required: true
        },
        valid: false
    },
    formIsValid: false
  };
    inputChangedHandler = (event, inputIdentifier) => {
        const updatedOrderForm = {
          ...this.state.orderForm 
        };
        const updatedFormElement = {
      ...updatedOrderForm[inputIdentifier] 
      };
    updatedFormElement.value = event.target.value; 
    updatedFormElement.valid = checkValidity(
      updatedFormElement.value,
      updatedFormElement.validation
    );

    updatedFormElement.touched = true; // ensures that the user types something in the input field
    updatedOrderForm[inputIdentifier] = updatedFormElement; 


    let formIsValid = true;
    for (let inputIdentifier in updatedOrderForm) {
      formIsValid = updatedOrderForm[inputIdentifier].valid && formIsValid;
    }

    this.setState({ orderForm: updatedOrderForm, formIsValid: formIsValid });
  };

  render() {

    const formElementsArray = [];
    for (let key in this.state.orderForm) {
      formElementsArray.push({
        id: key,
        config: this.state.orderForm[key]
      });

    }
    let form = (
      <form>
        {formElementsArray.map(formElement => {
          return (
            <Input
              inputtype={formElement.config.elementType}
              key={formElement.id}
              elementType={formElement.config.elementType}
              elementConfig={formElement.config.elementConfig}
              value={formElement.config.value}
              invalid={!formElement.config.valid}
              shouldValidate={formElement.config.validation}
              touched={formElement.config.touched}
              changed={event =>
                this.inputChangedHandler(
                  event,
                  formElement.id,
                  formElement.config.value
                )
              }
            />
          );
        })}
        <Button
          clicked={this.orderHandler}
          btnType="Success"
          disabled={!this.state.formIsValid}
        >
          PLACE ORDER HERE
        </Button>
      </form>
    );```

  validation function
export const checkValidity = (value, validation) => {
  let isValid = true;

  if (validation.required) {
    isValid = value.trim() !== "" && isValid;
  }
  if (validation.minLength) {
    isValid = value.length >= validation.minLength && isValid;
  }

  if (validation.maxLength) {
    isValid = value.length <= validation.maxLength && isValid;
  }
 return isValid;

};


【问题讨论】:

    标签: javascript reactjs forms validation


    【解决方案1】:

    我假设由于您最初在 state.orderForm.country 中将 country 设置为 false,除非进行更改,否则它将保持为 false。

    country: {
            elementType: "input",
            elementConfig: {
              type: "text",
              placeholder: "Country"
            },
            value: "England, UK",
            validation: {
              required: true
            },
            valid: false,
            touched: false
          }
    

    由于国家/地区已经有一个“英格兰,英国”的占位符 - 并且您认为这是一个有效的提交,然后将 valid 更改为 true,如下所示。如果用户输入无效数据,您的 checkValidity 函数应该覆盖您。

    country: {
                elementType: "input",
                elementConfig: {
                  type: "text",
                  placeholder: "Country"
                },
                value: "England, UK",
                validation: {
                  required: true
                },
                valid: true,
                touched: false
              }
    

    此外,您还可以将checkValidity 函数缩短为大致如下所示:

    export const checkValidity = (value, validation) => {
      if (
        value.trim() !== ""
        && value.length >= validation.minLength
        && value.length <= validation.maxLength
      ) {
        return true
      }
      return false
     }
    

    【讨论】:

    • 是的,行得通!我也会更新我的功能。对于电子邮件,我需要做同样的事情吗?但是输入不会总是预先填充,所以这是正确的吗? :email: { elementType: "input", elementConfig: { type: "email", placeholder: "Your E-Mail" }, value: this.props.email, validation: { required: true }, valid: this.props.email ? true : false, touched: false },
    • 是的,您还需要为value: this.props.email 设置默认的or 语句。见下文:email: { elementType: "input", elementConfig: { type: "email", placeholder: "Your E-Mail" }, value: this.props.email || '', validation: true, valid: { this.props.email ? true : false } }
    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 2022-01-25
    • 1970-01-01
    • 2020-04-24
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多