当表单验证出错时,如何防止提交表单按钮起作用?

How to prevent the button Submit form works when there is an error for form validation?

我已经构建了一个表单并为此表单添加了验证,必填字段。如果没有填写任何条目,则单击“计算保存范围”按钮时,它仍会链接到结果页面。当显示错误消息时,如何防止按钮链接到结果页面,否则它会起作用? 我的代码在这里

import React, { Component } from "react";
import "./style.css";
import { Button, Form, Row, Col} from "react-bootstrap";

class Calculator extends Component {
  constructor(props) {
    super(props);
    this.state = {
      numberBuilding: "",
      squareFootage: "",
      tenant: "",
      floor: "",
      bill: "",
      zipcode: "",
      squareFootageError: "",
      floorError: "",
      zipcodeError: ""
    };
  }

  handleSquare = (event) => {
    this.setState({ squareFootage: event.target.value });
  };

  handleFloor = (event) => {
    this.setState({ floor: event.target.value });
  };

  handleZipCode = (event) => {
    this.setState({ zipcode: event.target.value });
  };

  closeModal = () => this.setState({ isOpen: false });
  validate = () =>{
    let squareFootageError = " ";
    let floorError = " ";
    let zipcodeError = " ";

    if (!this.state.squareFootage){
      squareFootageError = "Please input a number, e.g. 12300";
    }

    if (!this.state.floor){
      floorError = "Please input a number of floors, e.g. 12";
    }

    if (!this.state.zipcode){
      zipcodeError = " Please input a ZIP code or PIN code if outside the US e.g., 10023 or L5V1N3";
    }

    if (squareFootageError || floorError || zipcodeError){
      this.setState({squareFootageError, floorError, zipcodeError });
      return false;
    }
    return true;
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const isValid = this.validate();
    if (isValid){
      console.log(this.state);
    }
    this.props.history.push({
      isOpen: true,
      state: {
        value:
          "$" +
          Math.floor(1.69 * this.state.squareFootage * (10 / 100)) +
          "- $" +
          Math.floor(1.69 * this.state.squareFootage * (30 / 100))
      }
    });
  
  };

  render() {
    return (
      <div className="calculator">
          
           {
          /*Condition*/ !this.state.isOpen ? (
            /** if true return form */

            <Form.Group as={Row} controlId="formHorizontalFootage">
              <Form.Label column sm={6}>
                Square footage of buildings*
              </Form.Label>
              <Col sm={6}>
                <Form.Control
                  type="squareFootage"
                  placeholder="sq ft"
                  value={this.state.squareFootage}
                  onChange={this.handleSquare}
                  required
                />
                <div style={{fontSize: 14, color: 'red'}}>{this.state.squareFootageError}</div>
                <Form.Text className="text-muted">
                Please input a number, e.g. 12300
                </Form.Text>
              </Col>
            </Form.Group>

           
            <Form.Group as={Row} controlId="formHorizontalNumber">
              <Form.Label column sm={6}>
                Number of floors*
              </Form.Label>
              <Col sm={6}>
                <Form.Control
                  type="number"
                  placeholder="number"
                  value={this.state.floor}
                  onChange={this.handleFloor}
                  required
                />
                <Form.Text className="text-muted">
                  Total number of floors across all buildings
                </Form.Text>
                <div style={{fontSize: 14, color: 'red'}}>{this.state.floorError}</div>
              </Col>
            </Form.Group>

            

            <Form.Group as={Row} controlId="formPlaintextZip">
              <Form.Label column sm={6}>
                Zip Code*
              </Form.Label>
              <Col sm={6}>
                <Form.Control
                  type="zipcode"
                  placeholder="xxxxx"
                  value={this.state.zipcode}
                  onChange={this.handleZipCode}
                  required
                />
                <div style={{fontSize: 14, color: 'red'}}>{this.state.zipcodeError}</div>
                <Form.Text className="text-muted">
                Please input a ZIP code or PIN code if outside the US e.g., 10023 or L5V1N3
                </Form.Text>
              </Col>
            </Form.Group>

            <Button onClick={this.handleSubmit}>
              Calculate your Savings Range
            </Button>
            <Form.Text className="text-muted">* Required Field</Form.Text>
          </Form>

) : (
  /** else return yourresult div */
  <div className="result">
    <h2>You could save between</h2>
    <h1>{this.state.value}</h1>
    <h2> annually </h2>
    &nbsp;&nbsp;
    <button onClick={this.handle}
    class="btn btn-secondary">
        Use Calculator again</button>
  </div>
)
}


</div>
    );
  }
}

export default Calculator;

你也可以在这里找到我的代码:https://codesandbox.io/s/calculation-form-uxip8?file=/src/components/Calculator.jsx

有人可以过来帮我一下吗?非常感谢!

如果 isValidfalse,您可以 return。

在这里分叉你的代码:https://codesandbox.io/s/calculation-form-forked-j3uhz?file=/src/components/Calculator.jsx

    if (isValid) {
      console.log(this.state);
    } else {
      return;
    }

此外,由于这些行,isValid 永远不会变为真:

    let squareFootageError = " ";
    let floorError = " ";
    let zipcodeError = " ";

通过将默认值设置为“”(由 space 组成的字符串),此条件:if (squareFootageError || floorError || zipcodeError) 始终有效,因此 validate() 永远不会 returns true。如果不清楚我也可以编辑你的codesandbox给你看。

您应该像这样将默认值设置为空字符串:

    let squareFootageError = "";
    let floorError = "";
    let zipcodeError = "";