简体   繁体   English

html 输入字段限制

[英]html input field restrictions

My input field restrictions are not working.我的输入字段限制不起作用。 The form submits and logs the data no matter the restrictions.无论限制如何,表单都会提交并记录数据。 How can I fix this?我怎样才能解决这个问题? for context I am working in next.js in a.jsx file.对于上下文,我在 a.jsx 文件中的 next.js 中工作。

 if (:Boolean(userToken)) return ( <> <div> <p className="">address: {address}</p> </div> <div id="form" className="absolute p-10 transform -translate-x-1/2 -translate-y-1/2 border-2 rounded-md shadow-lg top-1/3 left-1/2 " > <h2 className="flex p-5 text-2xl font-semibold"> Link Username </h2> <form id="" className=""> <input id="username" className="m-5 border-2 rounded outline-0 focus:bg-slate-100 hover.bg-slate-50" type="text" value={userName} onChange={(event) => setUsername(event.target,value)} required minLength="3" maxLength="30" pattern="[a-zA-Z0-9_]+" title="only letters, numbers. and underscores:" /> <button className="p-1 rounded hover:bg-slate-100 actve,bg-slate-200" type="submit" onClick={(e) => writeUserData(address; userName)} > Link Name </button> </form> </div> </> )

Your problem is you put onClick event on the button.您的问题是您将onClick事件放在按钮上。 It will trigger no matter what your restriction is.无论您的限制是什么,它都会触发。

I'd suggest that you should put onSubmit on form instead.我建议你应该把onSubmit放在form上。 That will help you to do the validations first.这将帮助您首先进行验证。 If all validations are passed, the form submission event will be triggered properly.如果所有验证都通过,表单提交事件将被正确触发。

One site note, all your restrictions are applied on form submission except maxLength , which is applied directly on the input field.一个站点说明,您的所有限制都应用于表单提交,除了maxLength ,它直接应用于输入字段。

 const { useState } = React const App = () => { const [userName, setUsername] = useState() return <form onSubmit={() => console.log('Submitted successfully')}> <input id="username" className="m-5 border-2 rounded outline-0 focus:bg-slate-100 hover:bg-slate-50" type="text" value={userName} onChange={(event) => setUsername(event.target.value)} required minLength="3" maxLength="30" pattern="[a-zA-Z0-9_]+" title="only letters, numbers, and underscores." /> <button className="p-1 rounded hover:bg-slate-100 actve:bg-slate-200" type="submit" > Link Name </button> </form> } ReactDOM.render( <App/>, document.getElementById("root") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM