我想驗證react
我的驗證代碼中的所有輸入,如下所示:
let isValid = {
name: false,
address: false,
postcode: false,
phone: false,
email: false
};
const validateInput = (e) => {
let currentInput = e.target
if (currentInput.name === 'name') {
if (currentInput.value !== 'undefined' && currentInput.value.match(/^[a-zA-Z] $/)) {
isValid.name = true;
} else {
isValid.name = false;
}
}
if (currentInput.name === 'address') {
if (currentInput.value !== 'undefined') {
isValid.address = true;
} else {
isValid.address = false;
}
}
if (currentInput.name === 'postcode') {
if (currentInput.value !== undefined && currentInput.value.match(/^[0-9] [-] [0-9] $/) && currentInput.value.length > 4) {
isValid.postcode = true;
} else {
isValid.postcode = false;
}
}
if (currentInput.name === 'phone') {
if (currentInput.value !== 'undefined' && currentInput.value.match(/^[0-9] $/) && currentInput.value.length > 7) {
isValid.phone = true;
} else {
isValid.phone = false;
}
}
if (currentInput.name === 'email') {
if (currentInput.value !== 'undefined' && currentInput.value.match(/^(([^<>()[\]\\.,;:\s@"] (\.[^<>()[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/)) {
isValid.email = true;
} else {
isValid.email = false;
}
}
console.log(isValid)
}
例如,當我在“名稱”中鍵入正確的值時,isValid.name 的值會變為真,然后當我在“地址”中寫一些想法時,isValid.address 會變為真,但 isValid.name 會為假如何解決?
{requiredInformations.map((el) => (
<>
<Label>{el.label}</Label>
<Input type={el.type} name={el.name} required onChange={(e) => { getInputValue(e); validateInput(e) }} />
</>
))}
uj5u.com熱心網友回復:
我建議您嘗試使用react-joi庫進行驗證React-Joi-Validation
使用起來簡單易行,您只需閱讀 npm 包主頁上的第一頁即可在代碼中實作您在此處嘗試的內容。
uj5u.com熱心網友回復:
您需要熟悉“狀態”、“道具”、“組件生命周期”等術語。使用 youtube 上的指南構建一個簡單的組件,您可以找到很多。
同時,這是一個驗證輸入的簡單組件:
function App() {
const [name, setName] = React.useState('');
const [address, setAddress] = React.useState('');
const isValid = React.useMemo(() => {
const result = {
name: false,
address: false,
};
if (name.match(/^[a-zA-Z] $/)) {
result.name = true;
} else {
result.name = false;
}
if (address !== '') {
result.address = true;
} else {
result.address = false;
}
return result;
}, [name, address]);
return (
<div>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
{isValid.name ? <p>Name is valid</p> : <p>Name is invalid</p>}
<br />
<input
placeholder="Address"
value={address}
onChange={(e) => setAddress(e.target.value)}
/>
{isValid.address ? <p>Adress is valid</p> : <p>Adress is invalid</p>}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/391718.html
標籤:javascript 反应 形式
