react dva 表单校验
import React,{ Component } from 'react'; import { connect } from 'dva'; import { WhiteSpace,NavBar ,List, InputItem ,Button,WingBlank } from 'antd-mobile'; import { createForm } from 'rc-form'; import * as UtilAPI from '../../utils/utils.js'; import * as FormAPI from '../../utils/form.js'; import styles from './Login.less'; const rules = { name: [{ required:true, message:"请输入手机号码" },{ pattern: /^1[3|5|7|8|9][0-9]\d{8}$/, message: "手机号码格式不正确"}], code:[{required:true,message:"条形码不能为空"}], msg:[{required:true,message:'短信验证码不能为空'}] }; class Login extends Component { constructor(props){ super(props); this.getFieldProps = this.props.form.getFieldProps; this.saveBaseInfo = this.saveBaseInfo.bind(this); this.handleScanInput =this.handleScanInput.bind(this); } handleScanInput(){ //调微信sdk接口 } saveBaseInfo(){ const ruleFields = FormAPI.getRuleFields(rules); console.log(ruleFields); const form = this.props.form; this.props.form.validateFields(ruleFields,(error,value)=>{ let flag = false; for(var key in error){ if(error[key].errors.length > 0 ){ UtilAPI.Toasting({type:"info", msg: error[key].errors[0].message}); flag = true; return; } } if(!flag){ let formdata = FormAPI.getFormData(form.getFieldsValue()); this.props.dispatch({ type:'login/saveItem', payload:{ itemType:"baseinfo", itemData:{ baseinfo:{ ...formdata } } } }) } }) } render(){ return( <div className={styles.main}> <NavBar className="top-nav-bar">登录{this.props.token}</NavBar> <WhiteSpace /> <WingBlank> <List> {<InputItem clear placeholder="手机号码" {...this.getFieldProps('name', { initialValue: this.props.baseinfo.name,rules: rules["name"]})} className="item-required">手机号码</InputItem>} </List> <WhiteSpace /> <List> {<InputItem clear placeholder="扫描条形码" {...this.getFieldProps('code',{initialValue:this.props.baseinfo.code,rules:rules["code"]})} className="item-required" onClick={this.handleScanInput}>扫描条形码</InputItem>} </List> <WhiteSpace /> <List> {<InputItem clear placeholder="短信验证码" {...this.getFieldProps('msg',{initialValue:this.props.baseinfo.msg,rules:rules["msg"]})} className="item-required" >短信验证码</InputItem>} </List> <WhiteSpace /> <Button type="primary">获取短信验证码</Button> <WhiteSpace /> <Button type="primary" onClick={ this.saveBaseInfo }>登录</Button> </WingBlank> </div> ); } } function mapStateToProps(state){ const { baseinfo,token } = state.login || {}; return { baseinfo : baseinfo || {}, token : token }; } export default connect(mapStateToProps)(createForm()(Login));