我正在使用Redux Form并创建验证,该检查将检查字段是否完全匹配X个字符。我的方法是确定输入的长度并针对指定的长度进行验证。我能够成功控制台记录每个字符输入,但是在尝试记录输入长度时收到错误。
如何确定Validator.js文件中输入的长度
错误消息:“ TypeError:无法读取未定义的属性'length'”
//component.js (Redux Form)
import React from 'react';
import {reduxForm, Field, SubmissionError, focus} from 'redux-form';
import Input from './input';
import {exactSix} from '../validators';
export class Contact extends React.Component {
// onSubmit(values) {}
render() {
return (
<form
onSubmit={this.props.handleSubmit(values =>
this.onSubmit(values)
)}>
<Field
name="content"
type="text"
component={Input}
label="Match"
validate={[exactSix]}
/>
<button
type="submit"
disabled={this.props.pristine || this.props.submitting}>
Send message
</button>
</form>
);
}
}
export default reduxForm({
form: 'contact',
onSubmitFail: (errors, dispatch) =>
dispatch(focus('contact', Object.keys(errors)[0]))
})(Contact);
//validator.js
export const exactSix = value => {
console.log(value);
console.log(values.length); //this line is highlighted within the error message
if(value.length === 6){
return undefined;
} else {
return 'must be exactly six';
}
}
答案 0 :(得分:0)
您需要检查value
是否未定义:
export const exactSix = value => {
return value && value.length !== length
? `must be exactly six`
: undefined;
};