簡體   English   中英

ReactJS 如何驗證所有輸入然后提交

[英]ReactJS how to validate all inputs then submit

我正在處理ReactJS中的form ,我有多個input (在小提琴中,這只是一個演示,實際代碼中大約有 10-15 個輸入)我想驗證所有輸入,如果所有輸入都有效,然后提交/發布到 api,到目前為止我嘗試的是這個JSFiddle

handleChange = (e) => {
  if (e.target.value.length >= 5) {
    this.setState({
      submit: true
    })
  } else {
    this.setState({
      submit: false
    })
  }
}

因此,為此,我定義了一個名為submit的 state ,如果submittrue ,則表單將提交並調用api 問題是,如果用戶填寫並驗證其中一個輸入,則將submit設置為true ,但我希望當用戶驗證所有輸入時, submit應設置為true

您應該有組件 state 來管理輸入驗證。 以下是我使用您的代碼並進行了編輯:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      submit: false,
      isValid: {
        "1": false,
        "2": false,
        "3": false,
        "4": false,
        "5": false
      }
    };
  }

  handleSubmit = e => {
    e.preventDefault();
    if (this.state.submit) {
      alert("POSTED TO API");
    } else {
      alert("fill the form!");
    }
  };

  checkValid = () => {
    if (
      Object.values(this.state.isValid).filter(value => !value).length === 0
    ) {
      this.setState({ ...this.state, submit: true });
    }
  };

  handleChange = (e, item) => {
    if (e.target.value.length >= 5) {
      this.setState(
        {
          ...this.state,
          isValid: { ...this.state.isValid, [`${item}`]: true }
        },
        this.checkValid
      );
    }
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        submit is: {this.state.submit ? "true" : "false"}
        <br />
        {[1, 2, 3, 4, 5].map(item => {
          return (
            <input
              name={"field" + item}
              type="text"
              onChange={e => {
                this.handleChange(e, item);
              }}
            />
          );
        })}
        <input type="submit" value="ok" />
      </form>
    );
  }
}

export default App;

您可以從 handleChange function 移動驗證。 像這樣更改您的 function (您需要為您的輸入設置名稱道具):

handleChange = (e) => {
  const filed = e.target.name;
  let newState = this.state;
  newState[field] = e.target.value;
  this.setState(newState);
}

並在 onSubmit function 檢查所有值是否有效,然后才調用您的 API。

  submit = (e) => {
    e.preventDefault();
    if(this.validate()){ . //validate function should be defined in your component - there you will have access to the component's state
      //call api
    } else {
     //show errors
    }
  }

也許您可以嘗試像這樣進行驗證,您可以創建驗證 function 然后您可以在提交 function 中實現驗證 function。

 constructor(props, context) {
    super(props, context);

    this.state = {
      email: "",
      user: "",
      submitted: false,
      errors: [],
      errorEmail: false,
      errorUserLenght: false,
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.validate = this.validate.bind(this);
  }

 validate(email, user) {
    const errors = [];

    if (email.length < 5) {
      this.setState({ errorEmail: true });
    } else {
      this.setState({ errorEmail: false });
    }
    if (email.split("").filter(x => x === "@").length !== 1) {
      this.setState({ errorEmail: true });
    } else {
      this.setState({ errorEmail: false });
    }

    if (email.indexOf(".") === -1) {
      this.setState({ errorEmail: true });
    } else {
      this.setState({ errorEmail: false });
    }

    if (user.length < 6) {
      this.setState({ errorUserLenght: true });
    } else {
      this.setState({ errorUserLenght: false });
    }


    return errors;
  }

  handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    this.setState({ [name]: value });
  }

  async handleSubmit(event) {
    event.preventDefault();

   await this.validate(email, password);

  // Here will be your code for POST
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM