Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React表单验证之一:Antd表单验证疑惑 #16

Open
tiodot opened this issue Jun 2, 2017 · 0 comments
Open

React表单验证之一:Antd表单验证疑惑 #16

tiodot opened this issue Jun 2, 2017 · 0 comments

Comments

@tiodot
Copy link
Owner

tiodot commented Jun 2, 2017

在开发React相关项目时,很多时候都需要对表单数据进行校验。之前做过基于antd的项目,对其方便但也比难用的表单验证影响很深刻。在用过的过程中总是想要是能像之前使用jQuery的Form Validator那样方便就好了。

先来看看antd是如何进行表单验证的,代码来源于antd中form的第二个示例

import { Form, Icon, Input, Button, Checkbox } from 'antd';
const FormItem = Form.Item;

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <FormItem>
          {getFieldDecorator('userName', {
            rules: [{ required: true, message: 'Please input your username!' }],
          })(
            <Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="Username" />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: 'Please input your Password!' }],
          })(
            <Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="Password" />
          )}
        </FormItem>
          <Button type="primary" htmlType="submit" className="login-form-button">
            Log in
          </Button>
        </FormItem>
      </Form>
    );
  }
}
const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
ReactDOM.render(<WrappedNormalLoginForm />, mountNode);

注册校验规则时,需要使用antd的form提供getFieldDecorator的函数。其函数定义形式为

getFieldDecorator(fieldName, fieldOption) => (Component) => ComponentWithExtraProps

getFieldDecorator会解析校验规则,然后保存,必要的时候会对字段进行校验。这块相对来说还是比较不易理解。

而对于jQuery的form validator 就简单多了,示例代码来源于jQuery Form Validator

<form action="/registration" method="POST">
  <p>
    User name (4 characters minimum, only alphanumeric characters):
    <input data-validation="length alphanumeric" data-validation-length="min4">
  </p>
  <p>
    Year (yyyy-mm-dd):
    <input data-validation="date" data-validation-format="yyyy-mm-dd">
  </p>
  <p>
    Website:
    <input data-validation="url">
  </p>
  <p>
    <input type="submit">
  </p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<script>
  $.validate({
    lang: 'es'
  });
</script>

如果需要框需要验证的,在dom元素上加data-validation属性就好,然后可以指定对应的校验的规则。简单粗暴,同时也很好理解。只是有一点不太爽,不能针对不同校验规则指定不同的错误消息。

对比两种校验方式,从代码层面,理解角度等我都比较倾向于jquery的这种,于是问题来了:
React是数据驱动,肯定不能引入jQuery然后操作dom进行校验,如何才能让React也能像jQuery对表单校验那样进行数据验证呢?能否写校验规则像下面一样:

class SimpleForm extends Component {
    onChange(e) {
        console.log(e.target.value);
    }
    onSubmit() {
        ....
    }
    render() {
        return (
            <div>
                <div>
                    Name:
                    <input name="name"
                           onChange={this.onChange.bind(this)}
                           type="text"
                           data-validation={[{required: true}]}/>
                </div>
                <div>
                    Age:
                    <input name="age"
                           type="text"
                           data-validation={[{required: true}]}/>
                </div>
                <button onClick={this.onSubmit.bind(this)}>submit</button>
            </div>
        );
    }
}

答案是肯定。预知后事如何,请听下回讲解。。。

@tiodot tiodot changed the title React表单验证之一:Antd表单验证能否杂交jQuery Form Validator? React表单验证之一:Antd表单验证疑惑 Jun 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant