Custom React Data Validation components

Source: Internet
Author: User



When we do a front-end form submission, we often encounter problems with verifying the data in the form. If a user submits data that is not valid, such as an incorrect format, a non-numeric type, a maximum length, a required item, a maximum and a minimum, and so on, we need to give the prompt information in the appropriate place. If the user fixes the data, we also need to hide the message.



There are some ready-made plugins that will make it easy for you to do this, and if you are using the knockout framework, you can use the Knockout-validation plugin. It's easy to use, like this piece of code below me:


Ko.validation.locale(‘zh-CN‘);
Ko.validation.rules[‘money‘] = {
    Validator: function (val) {
        If (val === ‘‘) return true;
        Return /^\d+(\.\d{1,2})?$/.test(val);
    },
    Message: ‘The amount entered is incorrect ‘
};
Ko.validation.rules[‘moneyNoZero‘] = {
    Validator: function (val) {
        If (val === ‘‘) return true;
        Return isNaN(val) || val != 0;
    },
    Message: ‘The amount entered cannot be 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);


More ways to use the documentation and examples on GitHub.






But what if we are using the REACT framework on the front-end, and how do we implement a similar function as above knockout? We can consider extracting this relatively independent function as a react component. Look at the following code:


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: ‘Must fill in ‘, isValid: false}, this);

    }
    // number validation
    If (this.state.number) {
      If (isNaN(fields)) {
        Return setStateQ({errors: ‘Please enter a number ‘, isValid: false}, this);
      }
      If (!isNilOrEmpty(this.state.min) && !isNaN(this.state.min) && Number(this.state.min) > Number(fields)) {
        Return setStateQ({errors: ‘The input value must be greater than or equal to ‘ + this.state.min, isValid: false}, this);
      }
      If (!isNilOrEmpty(this.state.max) && !isNaN(this.state.max) && Number(this.state.max) < Number(fields)) {
        Return setStateQ({errors: ‘The input value must be less than or equal to ‘ + 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: ‘the amount entered is incorrect ‘, isValid: false}, this);
      }
    }

    Return setStateQ({errors: ‘‘, isValid: true}, this);
  }

  Render() {
    Return <span className="text-danger">{this.state.errors}</span>
  }
} 


The validation items supported by this component are:


    • required: TRUE | False to check if a mandatory entry is required.
    • Number: true | False to check whether the value entered is a number.
      • If number is true, Max and Min can be used to verify the maximum and minimum values. The value of the Max and Min properties must be a valid number.
    • Money: TRUE | False to verify that the value entered is a valid currency format. The currency format must be a number, with a maximum of two decimal places allowed.


How do I use it?



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


<div className="item">
     <div className="col-xs-4">net price:</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">yuan</div>
     <div className="clear"></div>
</div> 


We add the price variable to the state of the parent component and bind the input control to the OnChange event so that when the user modifies the contents of the text box, the price the value of the variable can be passed into the validationinputs component in real time. In this way, thevalidationinputs component can immediately validate the incoming data against the pre-set rules by its own handlevalidation () method and decide whether to display an error message.



Note that when we reference the validationinputs component Here, we set a ref property, which is for the convenience of getting validationinputs in the parent component. The validation result of the component (success or failure). We can judge in the parent component by this method (assuming that the parent component references multiple validationinputs components, and each reference has a different ref value set):


// The parent component calls this method to determine if all entries are legal
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 the parent component submits the data, this method can be used to determine whether all the data items have passed validation, and if the validation is not passed, the form is not submitted.



Several other react-based data validation components appear to be used by the server side:



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



Custom React Data Validation components


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.