twitter-bootstrap 验证 React 中的表单输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41936524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validation of form input fields in React
提问by developer_beginning
<div className="form-group">
<label className="col-sm-0 control-label"> Name : </label>
<input
type="text"
value={this.state.UserName}
onChange={this.handleChangeUserName}
placeholder="Name"
pattern="[A-Za-z]{3}"
className="form-control"
/>
</div>
Hi, I am trying to validate a form input field in React using pattern validation. But it's not working. I am using validation as simple as pattern="[A-Za-z]{3}".
嗨,我正在尝试使用模式验证来验证 React 中的表单输入字段。但它不起作用。我使用的验证就像pattern="[A-Za-z]{3}".
Kindly let me know how to work this out. Putting validation in React Bootstrap component.
请让我知道如何解决这个问题。将验证放在 React Bootstrap 组件中。
采纳答案by Mayank Shukla
You are using the value property (means controlled component) of inputelement and updating the state in onChangemethod, So you can easily test this regex in onChangeand update the state only when the input will be valid.
您正在使用input元素的 value 属性(表示受控组件)并更新onChange方法中的状态,因此您可以轻松地测试此正则表达式onChange并仅在输入有效时更新状态。
Like this:
像这样:
handleChangeUserName(e){
if(e.target.value.match("^[a-zA-Z ]*$") != null){
this.setState({UserName: e.target.value});
}
}
Check the working code:
检查工作代码:
class HelloWidget extends React.Component {
constructor(){
super();
this.state={UserName:''}
this.handleChangeUserName = this.handleChangeUserName.bind(this);
}
handleChangeUserName(e){
if(e.target.value.match("^[a-zA-Z ]*$")!=null) {
this.setState({UserName: e.target.value});
}
}
render(){
return(
<div className="form-group">
<label className="col-sm-0 control-label" htmlFor="textinput"> Name : </label>
<input type="text" value={this.state.UserName} onChange={this.handleChangeUserName} placeholder="Name" className="form-control"></input>
</div>
)
}
}
ReactDOM.render(<HelloWidget/>, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container' />
Check the jsfiddlefor working example: https://jsfiddle.net/uL4fj4qL/11/
检查jsfiddle工作示例:https: //jsfiddle.net/uL4fj4qL/11/
Check this jsfiddle, Material-Ui snackbaradded to show the error, if user tries to enter the wrong value: https://jsfiddle.net/4zqwq1fj/
勾选此jsfiddle,Material-Ui snackbar加入到显示错误,如果用户尝试输入错误的值:https://jsfiddle.net/4zqwq1fj/
回答by tanguy_k
pattern="[A-Za-z]{3}"is a feature from HTML5.
pattern="[A-Za-z]{3}"是HTML5 的一项功能。
Complete solution here: https://codepen.io/tkrotoff/pen/qypXWZ?editors=0010
完整的解决方案在这里:https: //codepen.io/tkrotoff/pen/qypXWZ?editors=0010
If you only want to use default HTML5 validation:
如果您只想使用默认的 HTML5 验证:
class FormValidate extends React.Component {
state = {
username: ''
};
handleUsernameChange = e => {
console.log('handleUsernameChange()');
this.setState({
username: e.target.value
});
}
handleSubmit = e => {
console.log('handleSubmit() Submit form with state:', this.state);
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="username">Name</label>
<input
id="username"
name="username"
value={this.state.username}
onChange={this.handleUsernameChange}
placeholder="Name"
pattern="[A-Za-z]{3}"
className="form-control" />
</div>
<button className="btn btn-primary">Submit</button>
</form>
);
}
}
If you want to better integrate with Bootstrap 4:
如果您想更好地与Bootstrap 4集成:
class FormNoValidate extends React.Component {
state = {
username: '',
error: ''
};
handleUsernameChange = e => {
console.log('handleUsernameChange()');
const target = e.target;
this.setState({
username: target.value,
error: target.validationMessage
});
}
handleSubmit = e => {
console.log('handleSubmit() Submit form with state:', this.state);
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit} noValidate>
<div className="form-group">
<label htmlFor="username">Name</label>
<input
id="username"
name="username"
value={this.state.username}
onChange={this.handleUsernameChange}
placeholder="Name"
pattern="[A-Za-z]{3}"
className="form-control" />
<div className="invalid-feedback d-block">
{this.state.error}
</div>
</div>
<button className="btn btn-primary">Submit</button>
</form>
);
}
}
If you want to go further (more features, more control, better integration):
如果您想更进一步(更多功能、更多控制、更好的集成):
I've written a very simple React library to deal with form validation and that supports HTML5 attributes: https://github.com/tkrotoff/react-form-with-constraints
我编写了一个非常简单的 React 库来处理表单验证并支持 HTML5 属性:https: //github.com/tkrotoff/react-form-with-constraints
Examples here: https://github.com/tkrotoff/react-form-with-constraints/blob/master/README.md#examples
这里的例子:https: //github.com/tkrotoff/react-form-with-constraints/blob/master/README.md#examples
回答by Bill
with React hook, we can build custom hook to make validation much easier. with your example blow. you can easily by adding registermethod from react hook form: https://github.com/bluebill1049/react-hook-form
使用 React 钩子,我们可以构建自定义钩子以使验证更容易。以你的榜样打击。您可以轻松地通过register从 react hook 表单添加方法:https: //github.com/bluebill1049/react-hook-form
import React from 'react';
import useForm from 'react-hook-form';
function Test() {
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return {
<form className="form-group" onSubmit={handleSubmit(onSubmit)}>
<label className="col-sm-0 control-label"> Name : </label>
<input
type="text"
ref={register}
placeholder="Name"
pattern="[A-Za-z]{3}"
className="form-control"
/>
</div>
}
}


