我正在使用reduxForm 7.4.2,以简单的形式进行客户端验证。
表单是在页面加载时提交的,并显示如下错误:
我想防止表单加载时提交表单并显示错误 仅当用户单击“提交”按钮
时
以下是使用reduxForm的表单组件:
import React from 'react'
import { Field, reduxForm } from 'redux-form'
const renderField = ({ input, label, type, meta: { touched, error, warning } }) => {
console.log(error);
return(
<div className="form-group">
<label>{label}</label>
<input {...input} placeholder={label} type={type} className="form-control" />
{error && <div className="invalid-feedback d-block">{error}</div>}
</div>
)
}
const validate = values => {
const errors = {}
if (!values.name) {
errors.name = 'Name is Required'
} else if (values.name.length < 2) {
errors.name = 'Must be 2 characters or more'
}
if (!values.email) {
errors.email = 'Email is Required'
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
if (!values.password) {
errors.password = 'Password Required'
} else if (values.password.length < 6) {
errors.password = 'Password must be 6 characters'
}
return errors
}
const Form1Child=(props)=>{
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit} className="needs-validation" noValidate>
<Field name="name" type="text" component={renderField} label="Name"/>
<Field name="email" type="email" component={renderField} label="Email"/>
<Field name="password" type="password" component={renderField} label="Password"/>
<div>
<button className="btn btn-primary" type="submit" disabled={submitting}>Submit</button>
<button className="btn btn-default" type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
export default reduxForm({
form: 'form1',
validate
})(Form1Child)
这是父组件:
import React, { Component } from 'react'
import Form1Child from './Form1Child';
class Form1 extends Component {
constructor(){
super();
this.state={
}
}
handleSubmit=values=>{
alert(JSON.stringify(values));
}
render() {
return (
<Form1Child onSubmit={this.handleSubmit}/>
)
}
}
export default Form1;
答案 0 :(得分:0)
在您的validate函数中,执行以下操作:
browser = Watir::Browser.new(
:chrome,
'goog:chromeOptions' => {detach: true}
)
这将阻止操作
throw new SubmissionError('There were errors.')
答案 1 :(得分:0)
它的发生是因为您尚未检查字段是否脏。
在renderField
组件中,您尚未检查的字段是否被触摸。
在您的renderField
组件中替换此行
{error && <div className="invalid-feedback d-block">{error}</div>}
使用
{touched && error && <div className="invalid-feedback d-block">{error}</div>}
它应该可以工作。