Search code examples
react-reduxreact-nativeredux-form

String is undefined when trying to find its length


I am using redux-form in Ignite 2.0. I am trying to validate the values but whenever I try to find the length of a string, it gives me String is undefined

Here's my component

import React, { Component } from "react";
import { Field, reduxForm } from "redux-form";
import {
  Container,
  Content,
  Text,
  Button,
  View,
  Item,
  Input
} from "native-base";
import { StackNavigator } from "react-navigation";

const validate = value => {
  const error = {};
  error.name = "";
  error.password = "";
  const { name, password } = value;
  if (name === "undefined" || name === "") {
    error.name = "Empty";
  }
  if (password === "undefined" || password.length < 8) {
    error.password = "too short";
  }
  console.log("error", error);
};

class SignupForm extends Component {
  renderInput({
    input,
    label,
    placeholder,
    type,
    meta: { touched, error, warning }
  }) {
    var hasError = false;
    if (error !== undefined) {
      hasError = true;
    }
    return (
      <Item error={hasError}>
        <Input {...input} placeholder={placeholder} type={type} />
        {hasError ? <Text>{error}</Text> : <Text />}
      </Item>
    );
  }
  render() {
    const { handleSubmit } = this.props;

    return (
      <Container>
        <Content>
          <Field
            name="name"
            component={this.renderInput}
            label="Name"
            placeholder="Name"
            type="text"
          />
          <Field
            name="password"
            component={this.renderInput}
            placeholder="Password"
            label="Password"
            type="password"
          />
          <Button type="submit" onPress={handleSubmit}>
            <Text>Submit</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

export default reduxForm({
  form: "SignupForm",
  validate
})(SignupForm);

password.length keeps throwing the error TypeError:password is undefined Can anyone tell me what am I doing wrong or if I have missed something.

Thank you


Solution

  • if (password === "undefined" || password.length < 8) {
        error.password = "too short";
      }
    

    Here, replace "undefined" without double quote, undefined, since undefined is a primitive value.