Reputation: 1883
Login.js
import FormValidation from './validation/Form' //this is Form.js
constructor(props) {
super(props);
this.state = {
submit: true,
errorMessage: ''
};
}
<span>{this.state.errorMessage}</span>
<label><input type="text" name="tel" onBlur={this.FormValidation.validation.phone.blur} value={this.state.telValue}/></label>
Form.js
let validation = {}
const FormValidation = (e) => {
validation = {
phone: {
blur: (e) => {
let v = e.target.value;
console.log(v);
if(v.length <= 0){
this.setState({submit: false, errorMessage: 'can not empty!'})
}
}
}
}
}
export default FormValidation;
First I want to pass variable from input
to FormValidation
function to validate this input, problem is:
TypeError: Cannot read property 'phone' of undefined
On line onBlur={this.FormValidation.phone.blur}
Second problem is I want to setState
from Form.js
function to Login
compontent, as you see if length is less than zero it should make submit state to false
and set errorMessage
text.
Thanks in advance
Upvotes: 1
Views: 726
Reputation: 2391
I have added comments for the problematic parts of your code :
// FormValidation is a function, but in your input you are using it as an object.
const FormValidation = (e) => {
validation = {
phone: {
blur: (e) => {
let v = e.target.value;
console.log(v);
if (v.length <= 0) {
// FormValidation is not a React component, so it doesn't have a state. You should just return the error:
// return {submit: false, errorMessage: 'can not empty!'}
this.setState({submit: false, errorMessage: 'can not empty!'})
}
}
}
}
}
export default FormValidation;
Here is what you could do instead:
Login.js
import FormValidation from './validation/Form' //this is Form.js
constructor(props) {
super(props);
this.state = {
submit: true,
errorMessage: '',
telValue: ''
};
handleBlur = (e) => {
const value = e.target.value
const validationError = FormValidation.validation.phone.blur(value)
if (validationError) {
this.setState({
submit: validationError.submit,
errorMessage: validationError.errorMessage
})
} else {
this.setState({
telValue: value
})
}
}
render () {
return (
<label>
<span>
{this.state.errorMessage}
</span>
<input type="text" name="tel" onBlur={this.handleBlur} value={this.state.telValue}/>
</label>
)
}
}
Form.js
let validation = {}
const FormValidation = {
validation = {
phone: {
blur: (value) => {
console.log(value);
if (value.length <= 0) {
return {submit: false, errorMessage: 'can not empty!'}
}
}
}
}
}
export default FormValidation;
Upvotes: 1