Search code examples
reactjsmobxmobx-react-form

Error: The selected field is not defined (email)


I am trying to learn mobx-react-form and the validation part. I want a simple validation on email and also I want to do it with mobx-react-form. Given below is my code

const formFields = {
  email: {
    type: 'text',
    placeholder: 'Your Email Address',
    rules: 'required|email|string|between:5,50',
    value: ''
  }
};

@observer
class form extends React.Component {
  getValidation(): MobxReactForm {
    const hooks: any = {};

    const plugins: any = {
      dvr: dvr(validatorjs)
    };

    const formOptions: any = {
      validateOnChange: true
    };

    return new MobxReactForm({ formFields }, { plugins, hooks, formOptions });
  }
  @observable
  private form: MobxReactForm = this.getValidation();
  render() {
    return (
      <div>
        <form>
          <div>
            <FormControl margin="normal" fullWidth>
              <TextField {...this.form.$('email').bind()} />
            </FormControl>
            <Button variant="contained" color="primary" type="submit">
              Primary
            </Button>
          </div>
        </form>
      </div>
    );
  }
}
export default form;

It's showing this error


Solution

  • I think you have wrong key for fields:

      // It should be `fields` instead of `formFields`
      return new MobxReactForm({ fields }, { plugins, hooks, formOptions });
    

    Codesandbox