淺析JS中什么是自定義react數(shù)據(jù)驗(yàn)證組件
我們?cè)谧銮岸吮韱翁峤粫r(shí),經(jīng)常會(huì)遇到要對(duì)表單中的數(shù)據(jù)進(jìn)行校驗(yàn)的問(wèn)題。如果用戶提交的數(shù)據(jù)不合法,例如格式不正確、非數(shù)字類(lèi)型、超過(guò)最大長(zhǎng)度、是否必填項(xiàng)、最大值和最小值等等,我們需要在相應(yīng)的地方給出提示信息。如果用戶修正了數(shù)據(jù),我們還要將提示信息隱藏起來(lái)。
有一些現(xiàn)成的插件可以讓你非常方便地實(shí)現(xiàn)這一功能,如果你使用的是knockout框架,那么你可以借助于Knockout-Validation這一插件。使用起來(lái)很簡(jiǎn)單,例如我下面的這一段代碼:
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上的說(shuō)明文檔和示例。
但是,如果我們前端使用的是React框架,如何來(lái)實(shí)現(xiàn)和上面knockout類(lèi)似的功能呢?我們可以考慮將這一相對(duì)獨(dú)立的功能抽出來(lái),寫(xiě)成一個(gè)React組件??聪旅娴拇a:
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: '必須填寫(xiě)', isValid: false}, this); } // number validation if (this.state.number) { if (isNaN(fields)) { return setStateQ({errors: '請(qǐng)輸入數(shù)字', 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> } }
該組件支持的驗(yàn)證項(xiàng)有:
required:true | false 檢查是否必填項(xiàng)。
number:true | false 檢查輸入的值是否為數(shù)字。
如果number為true,可通過(guò)max和min來(lái)驗(yàn)證最大值和最小值。max和min屬性的值都必須為一個(gè)有效的數(shù)字。
money:true | false 驗(yàn)證輸入的值是否為一個(gè)有效的貨幣格式。貨幣格式必須為數(shù)字,最多允許有兩位小數(shù)。
如何使用?
我們?cè)诟附M件的render()方法中加入該組件的引用:
<p className="item"> <p className="col-xs-4">凈車(chē)價(jià):</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事件,以便用戶在修改了文本框中的內(nèi)容時(shí),price變量的值可以實(shí)時(shí)傳入到ValidationInputs組件中。這樣,ValidationInputs組件就可以立即通過(guò)自己的handleValidation()方法對(duì)傳入的數(shù)據(jù)按照預(yù)先設(shè)定的規(guī)則進(jìn)行驗(yàn)證,并決定是否顯示錯(cuò)誤信息。
注意,這里我們?cè)谝肰alidationInputs組件時(shí),設(shè)置了一個(gè)ref屬性,這是為了方便在父組件中獲得ValidationInputs組件的驗(yàn)證結(jié)果(成功或失?。?。我們可以在父組件中通過(guò)下面這個(gè)方法來(lái)進(jìn)行判斷(假設(shè)父組件中引用了多個(gè)ValidationInputs組件,并且每個(gè)引用都設(shè)置了不同的ref值):
// 父組件調(diào)用該方法來(lái)判斷所有的輸入項(xiàng)是否合法 checkInputs() { for (var r in this.refs) { var _ref = this.refs[r]; if (_ref instanceof ValidationInputs) { if (!_ref.state.isValid) return false; } } return true; }
這樣,我們?cè)诟附M件提交數(shù)據(jù)之前,可以通過(guò)這個(gè)方法來(lái)判斷所有的數(shù)據(jù)項(xiàng)是否都已經(jīng)通過(guò)驗(yàn)證,如果未通過(guò)驗(yàn)證,則不提交表單。
總結(jié)
以上所述是小編給大家介紹的JS中什么是自定義react數(shù)據(jù)驗(yàn)證組件,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
React DOM-diff 節(jié)點(diǎn)源碼解析
這篇文章主要為大家介紹了React DOM-diff節(jié)點(diǎn)源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02React實(shí)現(xiàn)一個(gè)通用骨架屏組件示例
骨架屏就是在頁(yè)面數(shù)據(jù)尚未加載前先給用戶展示出頁(yè)面的大致結(jié)構(gòu),直到請(qǐng)求數(shù)據(jù)返回后再渲染頁(yè)面,補(bǔ)充進(jìn)需要顯示的數(shù)據(jù)內(nèi)容,本文就介紹了React實(shí)現(xiàn)一個(gè)通用骨架屏組件示例,分享給大家,感興趣的可以了解一下2021-12-12React?Native系列之Recyclerlistview使用詳解
這篇文章主要為大家介紹了React?Native系列之Recyclerlistview使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10詳解React項(xiàng)目如何修改打包地址(編譯輸出文件地址)
這篇文章主要介紹了詳解React項(xiàng)目如何修改打包地址(編譯輸出文件地址),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03react時(shí)間分片實(shí)現(xiàn)流程詳解
實(shí)現(xiàn)react時(shí)間分片,主要內(nèi)容包括什么是時(shí)間分片、為什么需要時(shí)間分片、實(shí)現(xiàn)分片開(kāi)啟 - 固定、實(shí)現(xiàn)分片中斷、重啟 - 連續(xù)、分片重啟、實(shí)現(xiàn)延遲執(zhí)行 - 有間隔、時(shí)間分片異步執(zhí)行方案的演進(jìn)、時(shí)間分片簡(jiǎn)單實(shí)現(xiàn)、總結(jié)、基本概念、基礎(chǔ)應(yīng)用、原理機(jī)制和需要注意的事項(xiàng)等2022-11-11