Home >Web Front-end >JS Tutorial >What is a custom react data validation component in js (detailed explanation)

What is a custom react data validation component in js (detailed explanation)

青灯夜游
青灯夜游forward
2018-10-18 17:53:512447browse

This article brings you an introduction to what is a custom react data validation component. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

When we submit front-end forms, we often encounter the problem of verifying the data in the form. If the data submitted by the user is illegal, such as incorrect format, non-numeric type, exceeding the maximum length, required fields, maximum and minimum values, etc., we need to give prompt information in the corresponding place. If the user corrects the data, we also hide the prompt message.

There are some ready-made plug-ins that allow you to implement this function very conveniently. If you are using the knockout framework, then you can use the Knockout-Validation plug-in. It is very simple to use, such as the code below:

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);

For more usage methods, you can view the documentation and examples on github.

But, if we use the React framework on the front end, how can we achieve functions similar to knockout above? We can consider extracting this relatively independent function and writing it as a React component. Look at the code below:

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: &#39;输入值必须小于等于&#39; + 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>  }
}

The verification items supported by this component are:

  • ##required: true | false Check whether the item is required.

  • #number: true | false Checks whether the entered value is a number.

    • If number is true, the maximum and minimum values ​​can be verified through max and min. The value of both the max and min attributes must be a valid number.

  • money: true | false Verifies that the entered value is in a valid currency format. Currency format must be numeric, with up to two decimal places allowed.

how to use?

We add a reference to the component in the render() method of the parent component:

<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>
We add the

price variable to the state## of the parent component #, and bind the onChange event to the input control, so that when the user modifies the content in the text box, the value of the price variable can be passed in in real time to the ValidationInputs component. In this way, the ValidationInputs component can immediately verify the incoming data according to the preset rules through its own handleValidation() method, and decide whether to display an error message. Note that here we set a

ref

attribute when referencing the ValidationInputs component. This is to facilitate obtaining ValidationInputs in the parent component. The component's validation result (success or failure). We can use the following method to determine in the parent component (assuming that the parent component references multiple ValidationInputs components, and each reference is set to a different ref value):

// 父组件调用该方法来判断所有的输入项是否合法
checkInputs() {    
    for (var r in this.refs) {        
         var _ref = this.refs[r];        
         if (_ref instanceof ValidationInputs) {            
              if (!_ref.state.isValid) return false;
        }
    }    
    return true;
}
In this way, before we submit data in the parent component, we can use this method to determine whether all data items have passed verification. If they have not passed verification, the form will not be submitted.

The above is the detailed content of What is a custom react data validation component in js (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete