溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JavaScript中怎么自定義一個(gè)react數(shù)據(jù)驗(yàn)證組件

發(fā)布時(shí)間:2021-06-16 16:27:50 來(lái)源:億速云 閱讀:139 作者:Leah 欄目:web開發(fā)

JavaScript中怎么自定義一個(gè)react數(shù)據(jù)驗(yàn)證組件,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(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類似的功能呢?我們可以考慮將這一相對(duì)獨(dú)立的功能抽出來(lái),寫成一個(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: '必須填寫', 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()方法中加入該組件的引用:

<div className="item">
  <div className="col-xs-4">凈車價(jià):</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事件,以便用戶在修改了文本框中的內(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;
}

關(guān)于JavaScript中怎么自定義一個(gè)react數(shù)據(jù)驗(yàn)證組件問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI