简体   繁体   English

为什么我的必填字段显示错误为初始状态?

[英]Why my input field with required show error as initial state?

I have an input field that user need to fill. 我有一个用户需要填写的输入字段。 When the page is rendered i want the input field to be showing with no error red border because no value has been passed, i want to trigger the error only when the user type some value and then erased it. 呈现页面时,我希望输入字段显示为没有错误红色边框,因为没有传递任何值,我只想在用户键入一些值然后将其擦除时才触发错误。

The behavior that I want 我想要的行为

行为

The problem, I need to remove this red border on initial render 问题,我需要在初始渲染时删除此红色边框

边界

Here is code 这是代码

<div className="ipt-form-group">
      <input type="number" required className={this.state.activeCSS} placeholder="Qual a média de faturamento mensal?" min="0" onInput={this.changeView.bind(this)} onChange={this.changeRevenuesState.bind(this)}/>
    </div>
    <div className="ipt-form-group">
      <input type="number" required className={this.state.activeCSS} placeholder="Qual a média de despesas fixas mensais?" min="0" onInput={this.changeView.bind(this),() => this.callbackFunction()} onChange={this.changeAverageState.bind(this)}/>
    </div>

You need to init the validation on keyup on your form. 您需要在表单上的keyup上初始化验证。 I think you need something like this: 我认为您需要这样的东西:

 var validationRules = { city: { message: 'City cannot be empty', rule: 'notEmpty' }, address: { message: 'Address cannot be empty', rule: 'notEmpty' } }; var $inputs = $('#myForm :input'); var values = {}; $inputs.each(function() { $(this).on('keyup', function() { validation(this, validationRules[this.name]); }); }); function validation (input, ruleObj) { var isInvalid = false; if (ruleObj.rule === 'notEmpty') { if(input.value === '') { isInvalid = true; } else { isInvalid = false; } } if(isInvalid) { $(input).addClass('is-invalid'); } else { $(input).removeClass('is-invalid'); } console.log('Validated: ' + input.name); } 
 .is-invalid { border: 1px solid #ff0000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="myForm"> <label>Address</label> <input type="text" name="address"> <label>City</label> <input type="text" name="city"> </form> 

(Of course you can replace jQuery. It is bad practice to mix it with react as @Lojka said) (当然,您可以替换jQuery。按照@Lojka的说法,将它与react混合是不好的做法)

create your component, so it will get showBorder property. 创建您的组件,这样它将获得showBorder属性。

then you can create store with it being false by default, and after any update change it to true 那么您可以创建默认情况下为false的商店,并在进行任何更新后将其更改为true

and your store will handle all props for this input 您的商店将处理此输入的所有道具

read about flux / redux https://facebook.github.io/flux/docs/in-depth-overview.html#content 阅读有关flux / redux的信息https://facebook.github.io/flux/docs/in-depth-overview.html#content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM