簡體   English   中英

如何在 React JS 中將驗證添加到我的輸入字段

[英]How to add Validations to my Input Field in React JS

我有一個要添加驗證的輸入字段。 條件應該是amount不能為0,不能輸入任何字符。

我的反應代碼:

import React from 'react'
import { useState } from 'react';

function LoanInput() {

  const [loanAmount, setLoanAmount] = useState(0);

  const handleValidation = (e) => { 
    const formattedValue = (Number(e.target.value.replace(/\D/g, '')) || 0).toLocaleString();   
    setLoanAmount(formattedValue);
  }


  return (
    <div className="LoanAmountInput">
      <div className="LoanAmount">
        <label>Loan Amount</label>
        <input type="text" value={loanAmount} onChange={handleValidation} />
        <span style={{ color: "red" }}></span>
      </div>
    </div>
  );
}

export default LoanInput    

實際上,您可以使用瀏覽器使用輸入類型提供的默認驗證。 在您的情況下,您的代碼如下:

<input type="number" min="1" value={loanAmount} />

為什么采用這種方法?

  • 瀏覽器負責驗證和輸入清理。
  • 對於移動/平板設備,它只會向用戶顯示用於數據輸入的小鍵盤。

暫無
暫無

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

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