[英]validation in react hook form?
我有一個表單,我想在其中一個輸入上進行驗證,我使用 react hook form 。 這是我要申請的驗證:
const validateSheba=(str)=> {
var pattern = /IR[0-9]{24}/;
if (str.length !== 26) {
return false;
}
if (!pattern.test(str)) {
return false;
}
var newStr = str.substr(4);
var d1 = str.charCodeAt(0) - 65 + 10;
var d2 = str.charCodeAt(1) - 65 + 10;
newStr += d1.toString() + d2.toString() + str.substr(2, 2);
var remainder = this.iso7064Mod97_10(newStr);
if (remainder !== 1) {
return false;
}
return true;
};
這就是我使用它的方式:
<Input
name="Sheba"
placeholder=" شماره شبای بانکی"
ref={register({
required: true,
pattern: {
value:value=> validateSheba(value),
message: "نا معتبر",
},
})}
error={errors?.Sheba ? true : false}
helperText={errors?.Sheba?.message}
inputClassName={classes.input}
></Input>
它不起作用.. 我該怎么做?
在您的情況下,您使用的是驗證函數,而不是正則表達式。 prop模式用於正則表達式。
請檢查此代碼和框示例。 https://codesandbox.io/s/react-hook-form-js-forked-5kep0?file=/src/App.js
register 方法返回需要在輸入中注冊的多個值{ onChange, onBlur, name, ref }
。 例如
<Input {...register("test")} />
您將返回的對象分配給ref
。 我想這是錯誤的,但我不知道您的Input
組件是如何實現的。
這是一個可執行示例。 只需單擊底部的Run code snippet
。
const { useState, useEffect, useContext, useRef, useMemo } = React; const { useForm } = ReactHookForm; const App = () => { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data) => { alert(JSON.stringify(data)); }; // your form submit function which will invoke after successful validation const nameRequired = errors.name && errors.name.type === "required"; const namePattern = errors.name && errors.name.type === "pattern"; const wrongAge = errors.age; return ( <form onSubmit={handleSubmit(onSubmit)}> <div className="form-group"> <label>Name</label> <input {...register("name", { required: true, pattern: /^[A-Za-z]+$/i })} className="form-control" /> {nameRequired && <p>This field is required</p>} {namePattern && <p>Alphabetical characters only</p>} </div> <div className="form-group"> <label>Age</label> <input {...register("age", { min: 18, max: 99 })} className="form-control" /> {wrongAge && ( <p>You Must be older then 18 and younger then 99 years old</p> )} </div> <input type="submit" /> </form> ); }; ReactDOM.render(<App />, document.getElementById("root"));
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <script src="https://unpkg.com/react-hook-form@7.11.1/dist/index.umd.js"></script> <div id="root"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.