在进行后突变之前反应如何验证表单
Posted
技术标签:
【中文标题】在进行后突变之前反应如何验证表单【英文标题】:React how to validate form before making postmutation 【发布时间】:2020-10-04 02:10:23 【问题描述】:我有一个反应表单来向我的数据库添加一些数据。我正在使用 Prisma 和 Graphql。我将突变查询嵌套到一个按钮。因此,当单击按钮时,表单已提交,但我想知道如何在提交之前先验证是否已填写所有字段?
代码:
render()
const id, firstname, lastname = this.state
const UPDATE_MUTATION = gql`
mutation UpdateMutation($id:ID!, $firstname: String!, $lastname: String!)
updateClient(id:$id, firstname: $firstname, lastname: $lastname)
id
firstname
lastname
`
return (
<React.Fragment>
<Modal
...this.props
size="lg"
aria-labelledby="contained-modal-create-service"
centered
>
<Modal.Header closeButton >
<Modal.Title id="contained-modal-title-vcenter">Update service</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="flex flex-column mt3 client-row ">
<section className="form-group firstname">
<label>Firstname:</label>
<input
className="form-control "
value=firstname
onChange=e => this.setState( firstname: e.target.value )
type="text"
placeholder="A name for the service"
/>
</section>
<section className="form-group lastname">
<label>Lastname:</label>
<input
className="form-control "
value=lastname
onChange=e => this.setState( lastname: e.target.value )
type="text"
placeholder="The service cost"
/>
</section>
</div>
</Modal.Body>
<Modal.Footer>
<Mutation mutation=UPDATE_MUTATION
variables=id, firstname, lastname>
/* onCompleted=() => this.props.history.push('/') */
updateMutation =>
<button onClick=() => updateMutation(); this.props.onHide() ; window.location.reload(false) className="btn submit">Update</button>
</Mutation>
</Modal.Footer>
</Modal>
</React.Fragment>
【问题讨论】:
【参考方案1】:这是一个简单的例子:
const form = ()=>
const [form,setForm] = useState(userName:"",password:"")
const [error,setError] = useState(false)
const validateForm = ()=>
if(form.userName.length===0 && form.password.length===0)
return false
return true
const handleSubmit = ()=>
if(validateForm())
// do your stuff
else
setError(true)
const handleChange =(e)=>
if(error) setError(false);
const target = e
setForm(current=>(...current,[target.name]:target.value))
return (
<form onSubmit=handleSubmit>
<input type="text" name="userName" value=form.userName onChange=handleChange/>
<input type="password" name="password" value=form.password onChange=handleChange/>
<button type="submit">login</button>
error && <p> UserName and password are required!<p>
</form>
)
就是这样,但您可以通过使用 formik 和 yup validation library 之类的反应表单库来节省大量工作
【讨论】:
以上是关于在进行后突变之前反应如何验证表单的主要内容,如果未能解决你的问题,请参考以下文章