如何使用React正确验证输入值。JS?
-
21-12-2019 - |
题
我有一个简单的形式。所有组件和状态都保存在页面组件中。有2个显示标题和3个输入字段。第一个输入应该是文本,第二个和第三个应该是ints。当用户输入错误类型的数据时,我希望在输入字段旁边弹出错误消息。我的问题与React中的最佳实践有关。JS的
谁决定该值是有效的?我假设输入字段的唯一工作是将值引导回持有状态的组件,所以这是否意味着只有Page可以确定一个值是否有效?
那么我应该如何让弹出窗口出现?页面是否应该触发一个新的布尔状态元素,该元素将通过perp传递,该元素将告诉Adaptive_Input显示错误消息?
JS的:
/**
* @jsx React.DOM
*/
var Adaptive_Input = React.createClass({
handle_change: function(){
var new_text = this.refs.input.getDOMNode().value;
this.props.on_Input_Change(new_text);
},
render: function(){
return (
<div className='adaptive_placeholder_input_container'>
<input
className="adaptive_input"
type="text"
required="required"
onChange= {this.handle_change}
ref="input"
></input>
<label
className="adaptive_placeholder"
alt={this.props.initial}
placeholder={this.props.focused}
></label>
</div>
);
}
});
var Form = React.createClass({
render: function(){
return (
<form>
<Adaptive_Input
initial={'Name Input'}
focused={'Name Input'}
on_Input_Change={this.props.handle_text_input}
/>
<Adaptive_Input
initial={'Value 1'}
focused={'Value 1'}
on_Input_Change={this.props.handle_value_1_input}
/>
<Adaptive_Input
initial={'Value 2'}
focused={'Value 2'}
on_Input_Change={this.props.handle_value_2_input}
/>
</form>
);
}
});
var Page = React.createClass({
getInitialState: function(){
return {
Name : "No Name",
Value_1 : '0',
Value_2 : '0',
Display_Value: '0'
};
},
handle_text_input: function(new_text){
this.setState({
Name: new_text
});
},
handle_value_1_input: function(new_value){
console.log("===");
var updated_display = parseInt(new_value) + parseInt(this.state.Value_2);
updated_display = updated_display.toString();
this.setState({
Display_Value: updated_display
});
},
handle_value_2_input: function(new_value){
var updated_display = parseInt(this.state.Value_1) + parseInt(new_value);
updated_display = updated_display.toString();
this.setState({
Display_Value: updated_display
});
},
render: function(){
return(
<div>
<h2>{this.state.Name}</h2>
<h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
<Form
handle_text_input={this.handle_text_input}
handle_value_1_input = {this.handle_value_1_input}
handle_value_2_input = {this.handle_value_2_input}
/>
</div>
);
}
});
React.renderComponent(<Page />, document.body);
解决方案
如何使用React.js正确验证输入值?
但是你想要的。 React是用于渲染数据模型。数据模型应该知道什么是有效的。您可以使用骨干模型,JSON数据或想要表示数据的任何内容以及它的错误状态。
更具体地说:
React通常针对您的数据不可知。它用于渲染和处理事件。
要遵循的规则是:
- 元素可以改变他们的状态。
- 他们无法改变道具。
- 他们可以调用将改变顶级道具的回调。
如何决定是否应该是一个道具或国家?考虑一下:除了文本字段之外的应用程序是否要知道输入的值是坏的?如果没有,使它成为一个州。如果是,它应该是一个道具。
例如,如果您希望单独视图渲染“您在此页面上有2个错误。”然后,您的错误必须在TopleVel数据模型中已知。
那应该在哪里生活?
如果您的应用程序呈现骨干模型(例如),则模型本身将具有validate()方法和您可以使用的validateError属性。您可以呈现可以执行此操作的其他智能对象。 React还表示尝试将道具保留为最小并生成其余数据。因此,如果您有一个验证器(例如 https://github.com/flatiron/revalidator )那么你的验证可能会涓涓细流组件可以使用它的匹配验证检查道具,以查看它是否有效。
它在很大程度上取决于你。
(我是个人使用骨干模型并将它们渲染为反应。我有一个toplevel错误警报,我显示如果在任何地方出现错误,描述错误。)
其他提示
可以使用npm install --save redux-form
im编写一个简单的电子邮件并提交按钮表单,验证电子邮件并提交表单。使用Redux形式,默认情况下默认运行event.preventdefault()在html上onsubmit操作。
import React, {Component} from 'react';
import {reduxForm} from 'redux-form';
class LoginForm extends Component {
onSubmit(props) {
//do your submit stuff
}
render() {
const {fields: {email}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<input type="text" placeholder="Email"
className={`form-control ${email.touched && email.invalid ? 'has-error' : '' }`}
{...email}
/>
<span className="text-help">
{email.touched ? email.error : ''}
</span>
<input type="submit"/>
</form>
);
}
}
function validation(values) {
const errors = {};
const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;
if (!emailPattern.test(values.email)) {
errors.email = 'Enter a valid email';
}
return errors;
}
LoginForm = reduxForm({
form: 'LoginForm',
fields: ['email'],
validate: validation
}, null, null)(LoginForm);
export default LoginForm;
. 我已经写了这个库它允许您包装表单元素组件,并允许您以格式定义验证器: -
<Validation group="myGroup1"
validators={[
{
validator: (val) => !validator.isEmpty(val),
errorMessage: "Cannot be left empty"
},...
}]}>
<TextField value={this.state.value}
className={styles.inputStyles}
onChange={
(evt)=>{
console.log("you have typed: ", evt.target.value);
}
}/>
</Validation>
. 您的jsfiddle不再工作了。 我已经修复了它: http://jsfiddle.net/tkrotoff/bgc6e/40/使用React 16和ES6类。
class Adaptive_Input extends React.Component {
handle_change(e) {
var new_text = e.currentTarget.value;
this.props.on_Input_Change(new_text);
}
render() {
return (
<div className="adaptive_placeholder_input_container">
<input
className="adaptive_input"
type="text"
required="required"
onChange={this.handle_change.bind(this)} />
<label
className="adaptive_placeholder"
alt={this.props.initial}
placeholder={this.props.focused} />
</div>
);
}
}
class Form extends React.Component {
render() {
return (
<form>
<Adaptive_Input
initial={'Name Input'}
focused={'Name Input'}
on_Input_Change={this.props.handle_text_input} />
<Adaptive_Input
initial={'Value 1'}
focused={'Value 1'}
on_Input_Change={this.props.handle_value_1_input} />
<Adaptive_Input
initial={'Value 2'}
focused={'Value 2'}
on_Input_Change={this.props.handle_value_2_input} />
</form>
);
}
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: 'No Name',
Value_1: '0',
Value_2: '0',
Display_Value: '0'
};
}
handle_text_input(new_text) {
this.setState({
Name: new_text
});
}
handle_value_1_input(new_value) {
new_value = parseInt(new_value);
var updated_display = new_value + parseInt(this.state.Value_2);
updated_display = updated_display.toString();
this.setState({
Value_1: new_value,
Display_Value: updated_display
});
}
handle_value_2_input(new_value) {
new_value = parseInt(new_value);
var updated_display = parseInt(this.state.Value_1) + new_value;
updated_display = updated_display.toString();
this.setState({
Value_2: new_value,
Display_Value: updated_display
});
}
render() {
return(
<div>
<h2>{this.state.Name}</h2>
<h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
<Form
handle_text_input={this.handle_text_input.bind(this)}
handle_value_1_input={this.handle_value_1_input.bind(this)}
handle_value_2_input={this.handle_value_2_input.bind(this)}
/>
</div>
);
}
}
ReactDOM.render(<Page />, document.getElementById('app'));
.
现在与此库中的表单验证发送了相同的代码: https:/ /github.com/tkrotoff/reacon -form-with-constraints => http://jsfiddle.net/tkrotoff/k4qa4heg/
const { FormWithConstraints, FieldFeedbacks, FieldFeedback } = ReactFormWithConstraints;
class Adaptive_Input extends React.Component {
static contextTypes = {
form: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = {
field: undefined
};
this.fieldWillValidate = this.fieldWillValidate.bind(this);
this.fieldDidValidate = this.fieldDidValidate.bind(this);
}
componentWillMount() {
this.context.form.addFieldWillValidateEventListener(this.fieldWillValidate);
this.context.form.addFieldDidValidateEventListener(this.fieldDidValidate);
}
componentWillUnmount() {
this.context.form.removeFieldWillValidateEventListener(this.fieldWillValidate);
this.context.form.removeFieldDidValidateEventListener(this.fieldDidValidate);
}
fieldWillValidate(fieldName) {
if (fieldName === this.props.name) this.setState({field: undefined});
}
fieldDidValidate(field) {
if (field.name === this.props.name) this.setState({field});
}
handle_change(e) {
var new_text = e.currentTarget.value;
this.props.on_Input_Change(e, new_text);
}
render() {
const { field } = this.state;
let className = 'adaptive_placeholder_input_container';
if (field !== undefined) {
if (field.hasErrors()) className += ' error';
if (field.hasWarnings()) className += ' warning';
}
return (
<div className={className}>
<input
type={this.props.type}
name={this.props.name}
className="adaptive_input"
required
onChange={this.handle_change.bind(this)} />
<label
className="adaptive_placeholder"
alt={this.props.initial}
placeholder={this.props.focused} />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
Name: 'No Name',
Value_1: '0',
Value_2: '0',
Display_Value: '0'
};
}
handle_text_input(e, new_text) {
this.form.validateFields(e.currentTarget);
this.setState({
Name: new_text
});
}
handle_value_1_input(e, new_value) {
this.form.validateFields(e.currentTarget);
if (this.form.isValid()) {
new_value = parseInt(new_value);
var updated_display = new_value + parseInt(this.state.Value_2);
updated_display = updated_display.toString();
this.setState({
Value_1: new_value,
Display_Value: updated_display
});
}
else {
this.setState({
Display_Value: 'Error'
});
}
}
handle_value_2_input(e, new_value) {
this.form.validateFields(e.currentTarget);
if (this.form.isValid()) {
new_value = parseInt(new_value);
var updated_display = parseInt(this.state.Value_1) + new_value;
updated_display = updated_display.toString();
this.setState({
Value_2: new_value,
Display_Value: updated_display
});
}
else {
this.setState({
Display_Value: 'Error'
});
}
}
render() {
return(
<div>
<h2>Name: {this.state.Name}</h2>
<h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
<FormWithConstraints ref={form => this.form = form} noValidate>
<Adaptive_Input
type="text"
name="name_input"
initial={'Name Input'}
focused={'Name Input'}
on_Input_Change={this.handle_text_input.bind(this)} />
<FieldFeedbacks for="name_input">
<FieldFeedback when="*" error />
<FieldFeedback when={value => !/^\w+$/.test(value)} warning>Should only contain alphanumeric characters</FieldFeedback>
</FieldFeedbacks>
<Adaptive_Input
type="number"
name="value_1_input"
initial={'Value 1'}
focused={'Value 1'}
on_Input_Change={this.handle_value_1_input.bind(this)} />
<FieldFeedbacks for="value_1_input">
<FieldFeedback when="*" />
</FieldFeedbacks>
<Adaptive_Input
type="number"
name="value_2_input"
initial={'Value 2'}
focused={'Value 2'}
on_Input_Change={this.handle_value_2_input.bind(this)} />
<FieldFeedbacks for="value_2_input">
<FieldFeedback when="*" />
</FieldFeedbacks>
</FormWithConstraints>
</div>
);
}
}
ReactDOM.render(<Form />, document.getElementById('app'));
.
此处的拟议解决方案是喧嚣,因为我试图将其保持靠近原始的Jsfiddle。对于具有反应形式的响应 - 约束的正确表单验证,请检查 https:// github.com/tkrotoff/reacor-form-with-constraints#examples
使用 onChange={this.handleChange.bind(this, "name")
方法和 value={this.state.fields["name"]}
在输入文本字段中,下面创建span元素以显示错误,请参见下面的示例。
export default class Form extends Component {
constructor(){
super()
this.state ={
fields: {
name:'',
email: '',
message: ''
},
errors: {},
disabled : false
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
if(!fields["name"]){
formIsValid = false;
errors["name"] = "Name field cannot be empty";
}
if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
if(!fields["name"].match(/^[a-zA-Z]+$/)){
formIsValid = false;
errors["name"] = "Only letters";
}
}
if(!fields["email"]){
formIsValid = false;
errors["email"] = "Email field cannot be empty";
}
if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
if(!fields["message"]){
formIsValid = false;
errors["message"] = " Message field cannot be empty";
}
this.setState({errors: errors});
return formIsValid;
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
handleSubmit(e){
e.preventDefault();
if(this.handleValidation()){
console.log('validation successful')
}else{
console.log('validation failed')
}
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)} method="POST">
<div className="row">
<div className="col-25">
<label htmlFor="name">Name</label>
</div>
<div className="col-75">
<input type="text" placeholder="Enter Name" refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="exampleInputEmail1">Email address</label>
</div>
<div className="col-75">
<input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
<span style={{color: "red"}}>{this.state.errors["email"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="message">Message</label>
</div>
<div className="col-75">
<textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
<span style={{color: "red"}}>{this.state.errors["message"]}</span>
</div>
</div>
<div className="row">
<button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
</div>
</form>
)
}
}
. 我最近花了一周的一周,研究了很多解决方案,以在一个应用程序中验证我的表单。我从所有最盯着的人开始,但我找不到我所期望的人。几天后,在找到一个非常新的插件之前,我变得非常沮丧: https://github.com/kettanaito/reacont -advanced-form
Developper非常响应和他的解决方案,在我的研究之后,从我的角度来看,成为最盯着的人。我希望它能有所帮助,你会欣赏。
还有一个同样的问题 - form-container
在npm
我在过去使用了Redux-Form和Formik,最近反应引入挂钩,我为它建造了一个自定义钩子。请查看它,看看它是否使表单验证更容易。
github: https://github.com/bluebill1049/reacect-hook-full网站: http://reacect-hook-form.now.sh
使用此方法,您也不再执行受控输入。
以下示例:
import React from 'react'
import useForm from 'react-hook-form'
function App() {
const { register, handleSubmit, errors } = useForm() // initialise the hook
const onSubmit = (data) => { console.log(data) } // callback when validation pass
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstname" ref={register} /> {/* register an input */}
<input name="lastname" ref={register({ required: true })} /> {/* apply required validation */}
{errors.lastname && 'Last name is required.'} {/* error message */}
<input name="age" ref={register({ pattern: /\d+/ })} /> {/* apply a Refex validation */}
{errors.age && 'Please enter number for age.'} {/* error message */}
<input type="submit" />
</form>
)
}
. 有时,您可以在应用程序中拥有具有类似验证的多个字段。在这种情况下,我建议在保持此验证的情况下创建公共组件字段。
例如,让我们假设您在申请中的几个位置有强制性文本输入。您可以创建TextInput组件:constructor(props) {
super(props);
this.state = {
touched: false, error: '', class: '', value: ''
}
}
onValueChanged = (event) => {
let [error, validClass, value] = ["", "", event.target.value];
[error, validClass] = (!value && this.props.required) ?
["Value cannot be empty", "is-invalid"] : ["", "is-valid"]
this.props.onChange({value: value, error: error});
this.setState({
touched: true,
error: error,
class: validClass,
value: value
})
}
render() {
return (
<div>
<input type="text"
value={this.props.value}
onChange={this.onValueChanged}
className={"form-control " + this.state.class}
id="{this.props.id}"
placeholder={this.props.placeholder} />
{this.state.error ?
<div className="invalid-feedback">
{this.state.error}
</div> : null
}
</div>
)
}
.
然后,您可以在应用程序中的任何位置使用这样的组件:
constructor(props) {
super(props);
this.state = {
user: {firstName: '', lastName: ''},
formState: {
firstName: { error: '' },
lastName: { error: '' }
}
}
}
onFirstNameChange = (model) => {
let user = this.state.user;
user.firstName = model.value;
this.setState({
user: user,
formState: {...this.state.formState, firstName: { error: model.error }}
})
}
onLastNameChange = (model) => {
let user = this.state.user;
user.lastName = model.value;
this.setState({
user: user,
formState: {...this.state.formState, lastName: { error: model.error }}
})
}
onSubmit = (e) => {
// submit logic
}
render() {
return (
<form onSubmit={this.onSubmit}>
<TextInput id="input_firstName"
value={this.state.user.firstName}
onChange={this.onFirstNameChange}
required = {true}
placeholder="First name" />
<TextInput id="input_lastName"
value={this.state.user.lastName}
onChange={this.onLastNameChange}
required = {true}
placeholder="Last name" />
{this.state.formState.firstName.error || this.state.formState.lastName.error ?
<button type="submit" disabled className="btn btn-primary margin-left disabled">Save</button>
: <button type="submit" className="btn btn-primary margin-left">Save</button>
}
</form>
)
}
.
福利:
- 您不会重复验证逻辑
- 少于您的表单代码 - 它更可读
- 其他常见输入逻辑可以保持在组件 中
- 您遵循的反应规则,即组件应该尽可能愚蠢