您好,欢迎访问一九零五行业门户网

js中什么是自定义react数据验证组件(详解)

本篇文章给大家带来的内容是介绍什么是自定义react数据验证组件。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所助。
我们在做前端表单提交时,经常会遇到要对表单中的数据进行校验的问题。如果用户提交的数据不合法,例如格式不正确、非数字类型、超过最大长度、是否必填项、最大值和最小值等等,我们需要在相应的地方给出提示信息。如果用户修正了数据,我们还要将提示信息隐藏起来。
有一些现成的插件可以让你非常方便地实现这一功能,如果你使用的是knockout框架,那么你可以借助于knockout-validation这一插件。使用起来很简单,例如我下面的这一段代码:
ko.validation.locale('zh-cn');ko.validation.rules['money'] = {    validator: function (val) {               if (val === '') return true;        return /^\d+(\.\d{1,2})?$/.test(val);    },    message: '输入的金额不正确'};ko.validation.rules['moneynozero'] = {    validator: function (val) {                if (val === '') return true;        return isnan(val) || val != 0;    },    message: '输入的金额不能为0'};ko.validation.registerextenders();var model = {    msrp: ko.observable(0),    price: ko.observable().extend({ required: true, number: true, min: 10000, money: true, moneynozero: true }),    licence_service_fee: ko.observable().extend({ required: true, money: true }),    purchase_tax: ko.observable().extend({ required: true, money: true }),    vehicle_tax: ko.observable().extend({ required: true, money: true }),    insurance: ko.observable().extend({ required: true, money: true }),    commercial_insurance: ko.observable().extend({ required: true, money: true }),    mortgage: ko.observable(''),    interest_discount: ko.observable(''),    allowance: ko.observable().extend({ money: true }),    special_spec_fee_explain: ko.observable(''),    has_extra_fee: ko.observable(false),    is_new_energy: ko.observable(false)};model.extra_fee_explain = ko.observable().extend({    required: {        onlyif: function () {                       return model.has_extra_fee() === true;        }    }});model.extra_fee = ko.observable().extend({    required: {        onlyif: function () {                       return model.has_extra_fee() === true;        }    },    money: {        onlyif: function () {                        return model.has_extra_fee() === true;        }    }});model.new_energy_allowance_explain = ko.observable().extend({    required: {        onlyif: function () {                        return model.is_new_energy() === true;        }    }});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()) {        _total += number(model.extra_fee());    }        if (model.is_new_energy()) {        _total -= number(model.new_energy_allowance());    }        return isnan(_total) ? '0' : _total.tofixed(2).replace(/(\.0*$)|(0*$)/, '');});model.errors = ko.validation.group(model);ko.applybindings(model);
更多使用方法可以查看github上的说明文档和示例。
但是,如果我们前端使用的是react框架,如何来实现和上面knockout类似的功能呢?我们可以考虑将这一相对独立的功能抽出来,写成一个react组件。看下面的代码:
class validationinputs extends react.component {  constructor(props) {    super(props);    this.state = {      isvalid: true,      required: this.props.required,      number: this.props.number,      min: this.props.min,      max: this.props.max,      money: this.props.money,      data: null,      errors:     }  }  componentwillreceiveprops(nextprops) {       var that = this;        if (this.state.data !== nextprops.data) {            return setstateq({data: nextprops.data}, this).then(function () {                   return that.handlevalidation();      });    }  }  handlevalidation() {    var fields = this.state.data;    // required validation    if(this.state.required && isnilorempty(fields)){              return setstateq({errors: '必须填写', isvalid: false}, this);    }        // number validation    if (this.state.number) {            if (isnan(fields)) {                 return setstateq({errors: '请输入数字', isvalid: false}, this);      }            if (!isnilorempty(this.state.min) && !isnan(this.state.min) && number(this.state.min) > number(fields)) {               return setstateq({errors: '输入值必须大于等于' + this.state.min, isvalid: false}, this);      }            if (!isnilorempty(this.state.max) && !isnan(this.state.max) && number(this.state.max) < number(fields)) { return setstateq({errors: '输入值必须小于等于' + this.state.max, isvalid: false}, this); } } // money validation if (this.state.money) { if (fields.length > 0 && !/^\d+(\.\d{1,2})?$/.test(fields)) {                     return setstateq({errors: '输入的金额不正确', isvalid: false}, this);         }    }        return setstateq({errors: '', isvalid: true}, this);  }  render() {    return <span classname="text-danger">{this.state.errors}</span>  }}
该组件支持的验证项有:
required:true | false 检查是否必填项。
number:true | false 检查输入的值是否为数字。
如果number为true,可通过max和min来验证最大值和最小值。max和min属性的值都必须为一个有效的数字。
money:true | false 验证输入的值是否为一个有效的货币格式。货币格式必须为数字,最多允许有两位小数。
如何使用?
我们在父组件的render()方法中加入该组件的引用:
<p classname="item">    <p classname="col-xs-4">净车价:</p>    <p 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"/>    </p>    <p classname="col-xs-1 text-center">元</p>    <p classname="clear"></p></p>
我们将price变量加到父组件的state中,并给input控件绑定onchange事件,以便用户在修改了文本框中的内容时,price变量的值可以实时传入到validationinputs组件中。这样,validationinputs组件就可以立即通过自己的handlevalidation()方法对传入的数据按照预先设定的规则进行验证,并决定是否显示错误信息。
注意,这里我们在引用validationinputs组件时,设置了一个ref属性,这是为了方便在父组件中获得validationinputs组件的验证结果(成功或失败)。我们可以在父组件中通过下面这个方法来进行判断(假设父组件中引用了多个validationinputs组件,并且每个引用都设置了不同的ref值):
// 父组件调用该方法来判断所有的输入项是否合法checkinputs() {        for (var r in this.refs) {                 var _ref = this.refs[r];                 if (_ref instanceof validationinputs) {                          if (!_ref.state.isvalid) return false;        }    }        return true;}
这样,我们在父组件提交数据之前,可以通过这个方法来判断所有的数据项是否都已经通过验证,如果未通过验证,则不提交表单。
以上就是js中什么是自定义react数据验证组件(详解)的详细内容。
其它类似信息

推荐信息