表单验证错误时,如何防止按钮Submit form起作用?

如何解决表单验证错误时,如何防止按钮Submit form起作用?

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

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 = "";

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?