国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

js中自定義react數據驗證組件實例詳解

2024-05-06 16:46:30
字體:
來源:轉載
供稿:網友

我們在做前端表單提交時,經常會遇到要對表單中的數據進行校驗的問題。如果用戶提交的數據不合法,例如格式不正確、非數字類型、超過最大長度、是否必填項、最大值和最小值等等,我們需要在相應的地方給出提示信息。如果用戶修正了數據,我們還要將提示信息隱藏起來。

  有一些現成的插件可以讓你非常方便地實現這一功能,如果你使用的是knockout框架,那么你可以借助于Knockout-Validation這一插件。使用起來很簡單,例如我下面的這一段代碼:

js;" style="margin: 3px auto 0px; padding: 0px 0px 0px 5px; outline: none; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; width: 640px; line-height: 20px; clear: both; border-left: 3px solid rgb(108, 226, 108);">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()方法中加入該組件的引用:

<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值):

// 父組件調用該方法來判斷所有的輸入項是否合法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

總結

以上所述是小編給大家介紹的js中自定義react數據驗證組件實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 岗巴县| 湟中县| 浦江县| 开化县| 新沂市| 宣威市| 逊克县| 日喀则市| 常州市| 巴彦淖尔市| 监利县| 泸水县| 尚志市| 神农架林区| 凤城市| 辽宁省| 安丘市| 黄石市| 五莲县| 临清市| 分宜县| 湾仔区| 遂昌县| 张家界市| 遂川县| 蓝山县| 兴宁市| 大理市| 广灵县| 东兴市| 曲水县| 龙山县| 丽水市| 成安县| 镇宁| 微山县| 招远市| 老河口市| 楚雄市| 利川市| 平罗县|