作用
1. 添加验证规则并使用简单的语法使用它们.
2. 将外部错误传递给表单以始元素无效.
3. 动态的向表单添加元素,他们将注册或取消注册到表单.
4. 构建任何类型的表单元素组件,不只是传统输入,而是你自己想要的东西,并获得验证.
5. 使用处理程序处理表单的不同状态.
安装
1. 从此REPO下载并全局使用(Formsy)或requirejs
2. npm install formsy-react
与browserify一起安装并使用
3. 安装时 bower install formsy-react
使用
完整的API
formsy-react如何巧妙结合react.js用在表单验证中?
1. Formsy为您提供开箱即用的表格
import Formsy from 'formsy-react';
import MyOwnInput from './MyOwnInput'
const MyAppForm = React.createClass({
getInitialState(){
return {
canSubmit:false
}
},
enableButton(){
this.setState({
canSubmit:true
});
},
disableButton(){
this.setState({
canSubmit:false
});
},
submit(model){
someDep.saveEmail(model.email);
},
render(){
return (
< Formsy.Form onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton} > < MyOwnInput name="email " validationError="这不是有效的电子邮件 " validations="isEmail" required
/> <
button type="submit " disabled={ !this.state.canSubmit } >提交</ button ></ Formsy.Form >
);
}
});
2. 我建议把文本框当成一个组件(MyOwnInput)提出来更高效一些,将表单的值通过props传给组件,组件进行验证更为高效,如下图
import { withFormsy } from 'formsy-react';
import React from 'react';
class MyOwnInput extends React.Component {
modifyValue = event => {
this.props.setValue(event.currentTarget.value);
if(this.props.isValidValue(event.target.value) && this.props.onValid){
this.props.onValid()
}
}
render() {
const errorMessage = this.props.getErrorMessage();
const { type, getValue, className } = this.props
return (
<div className={className}>
<input
value={getValue() || ''}
onChange={this.modifyValue}
type={type}
/>
<span className="verify-error">{errorMessage}</span>
</div>
);
}
}
export default withFormsy(MyOwnInput);
3. input文本框里面的参数可参看API列表,也可以根据自己的规则自己定义,如下
import { addValidationRule } from 'formsy-react';
const Email = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; //邮箱验证
addValidationRule('isEmail', function (values, value) {
return Email.test(value)
});
后续free的时候还会为大家奉献上API使用示例~