经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JSJS库框架 » React » 查看文章
自定义react数据验证组件
来源:cnblogs  作者:Jaxu  时间:2018/10/19 9:12:57  对本文有异议

  我们在做前端表单提交时,经常会遇到要对表单中的数据进行校验的问题。如果用户提交的数据不合法,例如格式不正确、非数字类型、超过最大长度、是否必填项、最大值和最小值等等,我们需要在相应的地方给出提示信息。如果用户修正了数据,我们还要将提示信息隐藏起来。

  有一些现成的插件可以让你非常方便地实现这一功能,如果你使用的是knockout框架,那么你可以借助于Knockout-Validation这一插件。使用起来很简单,例如我下面的这一段代码:

  1. ko.validation.locale('zh-CN');
  2. ko.validation.rules['money'] = {
  3.     validator: function (val) {if (val === '') return true;return /^\d+(\.\d{1,2})?$/.test(val);
  4.     },
  5.     message: '输入的金额不正确'};
  6. ko.validation.rules['moneyNoZero'] = {
  7.     validator: function (val) {if (val === '') return true;return isNaN(val) || val != 0;
  8.     },
  9.     message: '输入的金额不能为0'};
  10. ko.validation.registerExtenders();var model = {
  11.     MSRP: ko.observable(0),
  12.     price: ko.observable().extend({ required: true, number: true, min: 10000, money: true, moneyNoZero: true }),
  13.     licence_service_fee: ko.observable().extend({ required: true, money: true }),
  14.     purchase_tax: ko.observable().extend({ required: true, money: true }),
  15.     vehicle_tax: ko.observable().extend({ required: true, money: true }),
  16.     insurance: ko.observable().extend({ required: true, money: true }),
  17.     commercial_insurance: ko.observable().extend({ required: true, money: true }),
  18.     mortgage: ko.observable(''),
  19.     interest_discount: ko.observable(''),
  20.     allowance: ko.observable().extend({ money: true }),
  21.     special_spec_fee_explain: ko.observable(''),
  22.     has_extra_fee: ko.observable(false),
  23.     is_new_energy: ko.observable(false)
  24. };
  25.  
  26. model.extra_fee_explain = ko.observable().extend({
  27.     required: {
  28.         onlyIf: function () {return model.has_extra_fee() === true;
  29.         }
  30.     }
  31. });
  32.  
  33. model.extra_fee = ko.observable().extend({
  34.     required: {
  35.         onlyIf: function () {return model.has_extra_fee() === true;
  36.         }
  37.     },
  38.     money: {
  39.         onlyIf: function () {return model.has_extra_fee() === true;
  40.         }
  41.     }
  42. });
  43.  
  44. model.new_energy_allowance_explain = ko.observable().extend({
  45.     required: {
  46.         onlyIf: function () {return model.is_new_energy() === true;
  47.         }
  48.     }
  49. });
  50.  
  51. model.total_price = ko.computed(function () {var _total = Number(model.price()) + Number(model.licence_service_fee()) +Number(model.purchase_tax()) + Number(model.vehicle_tax()) +Number(model.insurance()) + Number(model.commercial_insurance());if (model.has_extra_fee()) {
  52.         _total += Number(model.extra_fee());
  53.     }if (model.is_new_energy()) {
  54.         _total -= Number(model.new_energy_allowance());
  55.     }return isNaN(_total) ? '0' : _total.toFixed(2).replace(/(\.0*$)|(0*$)/, '');
  56. });
  57.  
  58. model.errors = ko.validation.group(model);
  59. ko.applyBindings(model);

  更多使用方法可以查看github上的说明文档和示例。

 

  但是,如果我们前端使用的是React框架,如何来实现和上面knockout类似的功能呢?我们可以考虑将这一相对独立的功能抽出来,写成一个React组件。看下面的代码:

  1. class ValidationInputs extends React.Component {
  2.   constructor(props) {
  3.     super(props);this.state = {
  4.       isValid: true,
  5.       required: this.props.required,
  6.       number: this.props.number,
  7.       min: this.props.min,
  8.       max: this.props.max,
  9.       money: this.props.money,
  10.       data: null,
  11.       errors: ""}
  12.   }
  13.  
  14.   componentWillReceiveProps(nextProps) {var that = this;if (this.state.data !== nextProps.data) {      return setStateQ({data: nextProps.data}, this).then(function () {return that.handleValidation();
  15.       });
  16.     }
  17.   }
  18.  
  19.   handleValidation() {var fields = this.state.data;// required validationif(this.state.required && isNilOrEmpty(fields)){      return setStateQ({errors: '必须填写', isValid: false}, this);
  20.  
  21.     }// number validationif (this.state.number) {      if (isNaN(fields)) {return setStateQ({errors: '请输入数字', isValid: false}, this);
  22.       }      if (!isNilOrEmpty(this.state.min) && !isNaN(this.state.min) && Number(this.state.min) > Number(fields)) {return setStateQ({errors: '输入值必须大于等于' + this.state.min, isValid: false}, this);
  23.       }      if (!isNilOrEmpty(this.state.max) && !isNaN(this.state.max) && Number(this.state.max) < Number(fields)) {return setStateQ({errors: '输入值必须小于等于' + this.state.max, isValid: false}, this);
  24.       }
  25.     }// money validationif (this.state.money) {      if (fields.length > 0 && !/^\d+(\.\d{1,2})?$/.test(fields)) {return setStateQ({errors: '输入的金额不正确', isValid: false}, this);
  26.       }
  27.     }return setStateQ({errors: '', isValid: true}, this);
  28.   }
  29.  
  30.   render() {return <span className="text-danger">{this.state.errors}</span>  }
  31. }

  该组件支持的验证项有:

  • required:true | false 检查是否必填项。

  • number:true | false 检查输入的值是否为数字。

    • 如果number为true,可通过max和min来验证最大值和最小值。max和min属性的值都必须为一个有效的数字。

  • money:true | false 验证输入的值是否为一个有效的货币格式。货币格式必须为数字,最多允许有两位小数。

  如何使用?

  我们在父组件的render()方法中加入该组件的引用:

  1. <div className="item"><div className="col-xs-4">净车价:</div><div className="col-xs-7"><input type="text" className="form-control" placeholder="0" value={this.state.price} onChange={this.changePrice.bind(this)}/><ValidationInputs ref="validation1" data={this.state.price} required="true" number="true" min="10000" max="99999999" money="true"/></div><div className="col-xs-1 text-center"></div><div className="clear"></div></div>

  我们将price变量加到父组件的state中,并给input控件绑定onChange事件,以便用户在修改了文本框中的内容时,price变量的值可以实时传入到ValidationInputs组件中。这样,ValidationInputs组件就可以立即通过自己的handleValidation()方法对传入的数据按照预先设定的规则进行验证,并决定是否显示错误信息。

  注意,这里我们在引用ValidationInputs组件时,设置了一个ref属性,这是为了方便在父组件中获得ValidationInputs组件的验证结果(成功或失败)。我们可以在父组件中通过下面这个方法来进行判断(假设父组件中引用了多个ValidationInputs组件,并且每个引用都设置了不同的ref值):

  1. // 父组件调用该方法来判断所有的输入项是否合法checkInputs() {for (var r in this.refs) {var _ref = this.refs[r];if (_ref instanceof ValidationInputs) {if (!_ref.state.isValid) return false;
  2.         }
  3.     }return true;
  4. }

   这样,我们在父组件提交数据之前,可以通过这个方法来判断所有的数据项是否都已经通过验证,如果未通过验证,则不提交表单。

  其它几个基于React的数据验证组件,不过貌似都是server端使用的:

  https://github.com/edwardfhsiao/react-inputs-validation

  https://github.com/learnetto/react-form-validation-demo

  https://learnetto.com/blog/how-to-do-simple-form-validation-in-reactjs

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号