Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize a react data validation component in JavaScript

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

In this article Xiaobian for you to introduce in detail "how to customize a react data validation component in JavaScript", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to customize a react data validation component in JavaScript" can help you solve your doubts.

The code is as follows:

Ko.validation.locale ('zh-CN'); ko.validation.rules [' money'] = {validator: function (val) {if (val =') return true; return / ^\ d + (\.\ d {1pime2})? $/ .test (val);}, message: 'incorrect amount entered'}; 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 * $) | (0mm $) /,');}); model.errors = ko.validation.group (model); ko.applyBindings (model)

For more information on how to use it, check the documentation and examples on github.

But if we are using the React framework at the front end, how can we achieve a function similar to that of the knockout above? We can consider taking out this relatively independent function and writing it 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: 'required', 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: '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: '输入值必须小于等于' + this.state.max, isValid: false}, this); } } // money validation if (this.state.money) { if (fields.length >

0 & &! / ^\ d + (\.\ d {1pr 2})? $/ .test (fields) {return setStateQ ({errors: 'incorrect amount entered', isValid: false}, this);} return setStateQ ({errors:', isValid: true}, this);} render () {return {this.state.errors}

The validators supported by this component are:

Required:true | false checks whether it is required.

Number:true | false checks whether the input value is numeric. ◦ if number is true, the maximum and minimum values can be verified by max and min. The value of both the max and min properties must be a valid number.

Money:true | false verifies that the value entered is in a valid currency format. The currency format must be numeric, with a maximum of two decimal places allowed.

How to use it?

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

Net car price: yuan

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 contents of the text box, the value of the price variable can be passed into the ValidationInputs component in real time. In this way, the ValidationInputs component can immediately validate the incoming data against predetermined rules through its own handleValidation () method and decide whether or not to display an error message.

Note that when we reference the ValidationInputs component, we set a ref property to facilitate the validation of the ValidationInputs component (success or failure) in the parent component. We can determine this in the parent component by the following method (assuming multiple ValidationInputs components are referenced in the parent component, and each reference is set to a different ref value):

/ / this method is called by the parent component to determine whether 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 } after reading this, the article "how to customize a react data validation component in JavaScript" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to learn more about related articles, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report