簡體   English   中英

驗證計算器中的輸入-React

[英]Validate inputs in a calculator - React

我已經寫了這個計算器來支付費用。 現在,我需要檢查輸入的內容是否為空+是一個數字,否則將引發錯誤消息,指出“該字段不能為空”。 我開始添加它,但在此過程中感到困惑。 在此示例中,處理錯誤處理的最佳/最干凈方法是什么? 也許我應該將錯誤處理工作放到一個單獨的組件中?

import React, { Component } from "react";

import styles from "./../styles.module.less";

class Calc extends Component {
    constructor(props) {
        super(props);
        this.state = {
            popoverOpen: false,
            cost: 0,
            homePrice: 0,
            downPaymentAmt: 0,
            downPaymentPrc: 0,
            termOfLoan: 0,
            annualInterestRate: 0,
            formError: '',
            inputValid: false
        };
    }

    handleStateChange = e => {
        const {
            target: { name, value },
        } = e;

        this.setState({ [name]: value });

    };
    handleCostChange = () => {
        const {
            homePrice,
            downPaymentAmt,
            termOfLoan,
            annualInterestRate,
        } = this.state;
        const principal = homePrice - downPaymentAmt;
        const lengthOfLoan = 12 * termOfLoan;
        const percentageRate = annualInterestRate / 1200;
        // Formula M = P[i(1+i)^n]/[(1+i)^n -1]
        const cost =
            (principal * percentageRate) /
            (1 - Math.pow(1 + percentageRate, lengthOfLoan * -1)).toString();
        this.setState({
            cost: cost.toFixed(2),
        });
    };

    render() {
        return (
            <div>
                <div className={styles.row}>

                    <div className={styles.col12}>
                        <h1 className={styles.calch1}>
                           Your home-buying by numbers
                        </h1>
                        <div
                            className={`${styles.positionRelative} ${
                                styles.formGroup
                            }`}>
                            <label htmlFor="name" >
                                Home price
                            </label>
                            <label s" formError={this.state.formError}>The field can't be empty</label>
                            <div className={styles.inputGroup}>
                                <div className={styles.inputGroupPrepend}>
                                    <span className={styles.inputGroupText}>
                                        $
                                    </span>
                                </div>
                                <input
                                    type="text"
                                    id="input3-group1"
                                    className={styles.formControl}
                                    name="homePrice"
                                    value={this.state.value}
                                    onChange={this.handleStateChange}
                                    placeholder="Amount of home's selling price"
                                />
                            </div>
                        </div>
                    </div>
                </div>
                <div className={styles.row}>
                    <div className={styles.col12}>
                        <div
                            className={`${styles.positionRelative} ${
                                styles.formGroup
                            }`}>
                            <label htmlFor="name" className="">
                                Loan program
                            </label>
                            <div className={styles.inputGroup}>
                                <input
                                    type="text"
                                    id="name"
                                    required=""
                                    className={styles.formControl}
                                    name="termOfLoan"
                                    value={this.state.value}
                                    onChange={this.handleStateChange}
                                    placeholder="Original number of years to pay off your mortgage"
                                />
                            </div>

                        </div>
                    </div>
                </div>

                    <div className={`${styles.col6} ${styles.colsm4}`}>
                        <div
                            className={`${styles.positionRelative} ${
                                styles.formGroup
                            }`}>
                            <label
                                htmlFor="name"
                                className=""
                                style={{ display: "block" }}>
                                &nbsp;
                            </label>
                            <button
                                className={`${styles.btn} ${
                                    styles.btnWarning
                                } ${styles.btnSm}`}
                                style={{
                                    fonSize: 16,
                                    height: "35px",
                                    color: "white",
                                }}
                                onClick={this.handleCostChange}>
                                Calculate!
                            </button>
                        </div>
                    </div>
                </div>
                <div className={styles.row}>
                    <div className={styles.col}>
                        <h2 className={styles.calch2}>
                          Your monthly mortgage 
                        </h2>
                        <div className={styles.tableResponsive}>
                            <table
                                className={`${styles.borderLess} ${
                                    styles.table
                                }`}>
                                {/* <thead>
                                    <tr>
                                        <th>Estimated monthly</th>
                                        <th>taxes</th>
                                        <th>Insurance</th>
                                        <th>P&amp;I</th>
                                    </tr>
                                </thead> */}
                                <tbody>
                                    <tr className={styles.output}>
                                        <td>
                                            ${this.state.cost.toLocaleString()}
                                        </td>
                                       <td className={styles.tdlabel}>
                                           PER MONTH
                                       </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default Calc;

您可以監聽onBlur事件。 當用戶離開輸入字段時發生。 因此,在輸入字段中添加onBlur事件監聽器。

例如:對於房屋價格

<input
      type="text"
      id="input3-group1"
      className={styles.formControl}
      name="homePrice"
      // assign value as this.state.homePrice
      value={this.state.homePrice}
      // Add onBlur and use handleValidation event handler
      onBlur={this.handleValidation}
      onChange={this.handleStateChange}
      placeholder="Amount of home's selling price"
  />

// for testing add this line just below the input field 
// it will display form error              
{ this.state.formError && <span>{this.state.formError} </span> }

現在將handleValidation方法添加到您的組件中

handleValidation = (e) => {
         let { value } = e.target
         // check if value is empty or not       
         if (value.trim().length === 0) {
            this.setState({formError: 'Input field is required'}) 
            return
         // check if value is number or not
         } else if (isNaN(Number(value))) {
            this.setState({formError: 'Input field value must be a number'}) 
            return
        } else {
            this.setState({ formError: ''})
        }
    } 

更新

handleCostChange = (e) => {
        // for testing only not needed
        let { value } = e.target; 
        // Checking whether "e.target.value" on button is empty or not
        console.log('some',value,'text') // some text
        console.log(value.trim().length === 0)  // true

        const {
            homePrice,
            downPaymentAmt,
            termOfLoan,
            annualInterestRate,
        } = this.state;

        // updates
        if (homePrice.trim().length === 0) {
            this.setState({formError: 'Input Fields are required'}) 
            return
        } else if (isNaN(Number(homePrice))) {
            this.setState({formError: 'Input Fields must be number'}) 
            return
        }

        const principal = homePrice - downPaymentAmt;
        const lengthOfLoan = 12 * termOfLoan;
        const percentageRate = annualInterestRate / 1200;
        // Formula M = P[i(1+i)^n]/[(1+i)^n -1]
        const cost =
            (principal * percentageRate) /
            (1 - Math.pow(1 + percentageRate, lengthOfLoan * -1)).toString();
        this.setState({
            cost: cost.toFixed(2),
            // update
            formError: ''
        });
    };

還要改變

this.state = {homePrice: 0}

this.state = {homePrice: ''}

這是必需的,因為我使用了trim()方法,它是一個字符串方法。 因此,當您提交而不觸摸輸入字段時,您將得到一個錯誤。

暫無
暫無

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

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