React的一个表单验证器formsy-react

作用

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使用示例~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值