javascript 如果为空或数字,则响应输入验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54450445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Input validation if empty or number
提问by Max T
I've created this method that gets the state of the calculator input and checks if its empty or not. I need help with two things:
我创建了这个方法来获取计算器输入的状态并检查它是否为空。我需要两件事的帮助:
- What's the cleanest way to add here a validation to check if each input is also a number and outputs and error "Input must be a number"
Currently I have one error message that fires whether all the inputs are present or not, where what I want is for it to validate each input separately and fire an error under each one. How do I do it but still keep this function concise?
constructor(props) { super(props); this.state = { price: 0, downP: 0, term: 0, interest: 0, error: '' }; } handleValidation = () => { const { price, downP, loan, interest, } = this.state; let error = ''; let formIsValid = true; if(!price || !downP || !loan || !interest){ formIsValid = false; error = "Input fields cannot be empty"; } this.setState({error: error}); return formIsValid; }And then this is the error message
<span style={{color: "red"}}>{this.state.error}</span>
- 在此处添加验证以检查每个输入是否也是数字和输出以及错误“输入必须是数字”的最简洁方法是什么?
目前我有一条错误消息,无论所有输入是否存在都会触发,我想要的是它分别验证每个输入并在每个输入下触发一个错误。我该怎么做但仍然保持这个功能简洁?
constructor(props) { super(props); this.state = { price: 0, downP: 0, term: 0, interest: 0, error: '' }; } handleValidation = () => { const { price, downP, loan, interest, } = this.state; let error = ''; let formIsValid = true; if(!price || !downP || !loan || !interest){ formIsValid = false; error = "Input fields cannot be empty"; } this.setState({error: error}); return formIsValid; }然后这是错误信息
<span style={{color: "red"}}>{this.state.error}</span>
回答by Andy Noelker
A straightforward way of handling multiple objects needing validation is to store an errorsobject in your state that has a property for each input field. Then you conditionally render the error underneath each input field depending on whether or not it has an error. Here is a very basic example:
处理需要验证的多个对象的一种直接方法是errors在您的状态中存储一个对象,该对象具有每个输入字段的属性。然后你有条件地在每个输入字段下呈现错误,具体取决于它是否有错误。这是一个非常基本的例子:
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
price: 0, downP: 0, term: 0, interest: 0,
errors: { price: '', downP: '', term: '', interest: '' }
};
}
handleValidation = () => {
const { price, downP, loan, interest } = this.state;
let errors = { price: '', downP: '', term: '', interest: '' };
if (!price) {
errors.price = 'Price is required';
} else if (isNaN(price)) {
errors.price = 'Price must be a number';
}
if (!downP) {
errors.downP = 'Down Payment is required';
}
// Rest of validation conditions go here...
this.setState({ errors });
}
render() {
const { errors } = this.state;
return (
<form>
<input name="price" value={this.state.price} onChange={this.handleChange} />
{errors.price != '' && <span style={{color: "red"}}>{this.state.errors.price}</span>}
<input name="downP" value={this.state.downP} onChange={this.handleChange} />
{errors.downP != '' && <span style={{color: "red"}}>{this.state.errors.downP}</span>}
{/** Rest of components go here */}
</form>
);
}
}
You can choose whether or not to run validation once the form submits or on every keypress and that will affect how when those messages appear and disappear, but this should give you an idea on how you would manage error messages specific to each input field.
您可以选择是否在表单提交后或在每次按键时运行验证,这将影响这些消息何时出现和消失的方式,但这应该让您了解如何管理特定于每个输入字段的错误消息。
回答by Shevchenko Viktor
If you want to keep your error messages separate I would recommend to reorganize your state.
如果您想将错误消息分开,我建议您重新组织您的状态。
So scalable solution (you may add more controls by just adding them to state) may look like:
因此可扩展的解决方案(您可以通过将它们添加到状态来添加更多控件)可能如下所示:
class NumberControlsWithErrorMessage extends React.Component {
constructor(props) {
super(props);
this.state = {
inputs: [
{ name: 'price', value: 0, error: ''},
{ name: 'downP', value: 0, error: '' },
{ name: 'term', value: 0, error: '' },
{ name: 'interest', value: 0, error: '' }
]
};
}
handleInputChange = (idx, event) => {
const target = event.target;
const name = target.name;
let error = '';
if (isNaN(target.value)) {
error = `${name} field can only be number`
}
if (!target.value) {
error = `${name} field cannot be empty`
}
this.state.inputs[idx] = {
...this.state.inputs[idx],
value: target.value,
error
}
this.setState({
inputs: [...this.state.inputs]
});
}
render() {
return (
<form>
{this.state.inputs.map((input, idx) => (
<div>
<label htmlFor="">{input.name}</label>
<input type="text" value={input.value} onChange={(e) => this.handleInputChange(idx, e)}/>
{input.error && <span>{input.error}</span> }
</div>
))}
</form>
);
}
}
Also if you are building a complex form, you may want to try some React solution for forms, where all the mechanism for listening to events, state updates, validatoin are already handled for you. Like reactive-mobx-form
此外,如果您正在构建一个复杂的表单,您可能想尝试一些 React 表单解决方案,其中所有用于侦听事件、状态更新、验证的机制都已经为您处理。像reactive-mobx-form
回答by dabishan
You can do this:
你可以这样做:
handleValidation() {
const { price, downP,loan, interest} = this.state;
// only each block with generate error
if (!price || isNaN(price)) {
this.setState({ error: 'price is not valid' });
} else if (!downP || isNaN(downP)) {
this.setState({ error: 'downP is not valid' });
} else {
this.setState({error: ""})
// submit code here
}
}
Note: you dont need to return anything. It will update the error state and only submit the form if it goes into no error (else{}) part
注意:您不需要返回任何东西。它将更新错误状态,并且只有在没有错误 (else{}) 部分时才提交表单
and for render() part add this:
和 render() 部分添加这个:
{(this.state.error !== '')
? <span style={{color: "red"}}>{this.state.error}</span>
: ''
}
If you want validation msg on each add errPrice, errDownPand so on to the state, and check for them in render like (this.state.errPrice!== '') {}and so on.
如果你想在每个 add 上验证 msg errPrice,errDownP等等到状态,并在渲染中检查它们(this.state.errPrice!== '') {}等等。
回答by Mark
One solution assuming you want a one size fits all error message only checking if it was a number or not would be to put them into an array and set error if the input is not a number.
假设您想要一个适合所有错误消息的一种解决方案仅检查它是否是数字,则将它们放入数组并在输入不是数字时设置错误。
const inputs = [ price, downP, loan, interest ]
inputs.map(input => {
if (!input || isNaN(input)){
error = "Input must be a number"
formIsValid = false
}
}
this.setState({error})
Something like that maybe.
也许是这样的。

