自定义react数据验证组件
- 时间:
- 浏览:0
- 来源:大发快三_快三总代_大发快三总代
朋友在做前端表单提交时,老要 会遇到要对表单中的数据进行校验的问題。将会用户提交的数据不合法,累似 格式不正确、非数字类型、超过最大长度、有无必填项、最大值和最小值等等,朋友需用在相应的地方给出提示信息。将会用户修正了数据,朋友需用将提示信息隐藏起来。
有其他现成的插件要能让我非常方便地实现这名 功能,将会你使用的是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: 100000, 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()土办法中加入该组件的引用:
<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="100000" 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值):
// 父组件调用该土办法来判断所有的输入项有无合法 checkInputs() { for (var r in this.refs) { var _ref = this.refs[r]; if (_ref instanceof ValidationInputs) { if (!_ref.state.isValid) return false; } } return true; }
那我,朋友在父组件提交数据以前,要能通过这名 土办法来判断所有的数据项有无都将会通过验证,将会未通过验证,则不提交表单。
其它哪几个基于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