簡體   English   中英

當表單驗證出現錯誤時,如何防止按鈕提交表單工作?

[英]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您可以返回。

在這里分叉你的代碼: 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 = " ";

通過將默認值設置為“”(一個由空格組成的字符串),這個條件: if (squareFootageError || floorError || zipcodeError)始終有效,因此validate()永遠不會返回true 如果不清楚,我也可以編輯您的代碼和框以顯示給您。

您應將默認值設置為空字符串,如下所示:

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

暫無
暫無

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

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