Skip to content

How to onBlur (mui v5 example)

NewOldMax edited this page Sep 22, 2021 · 1 revision

If you want to validate inputs with onBlur event, you can do this following way (if you want to use required validation rule with onBlur you should add true as second parameter to validate function):

https://codesandbox.io/s/moj233r2lx

import React from "react";
import Button from "@mui/material/Button";
import { TextValidator, ValidatorForm } from "react-material-ui-form-validator";

export default class SomeComponent extends React.Component {
  state = {
    data: { email: "" }
  };

  emailRef = React.createRef();

  handleValue = event => {
    const { data } = this.state;
    data[event.target.name] = event.target.value;
    this.setState({ data });
  };

  handleBlur = event => {
    const { name, value } = event.target;
    if (name === "email") {
      // set true as second parameter to onBlur required validation
      this.emailRef.current.validate(value);
    }
  };

  handleSubmit = () => {
    // your submit logic
  };

  render() {
    const { data } = this.state;
    return (
      <ValidatorForm
        ref={r => (this.form = r)}
        onSubmit={this.handleSubmit}
        instantValidate={false}
      >
        <TextValidator
          ref={this.emailRef}
          name="email"
          label="email"
          value={data.email}
          onBlur={this.handleBlur}
          onChange={this.handleValue}
          validators={["isEmail", "required"]}
          errorMessages={["wrong email", "this field is required"]}
        />
        <br />
        <Button onClick={() => this.form.submit()}>submit</Button>
      </ValidatorForm>
    );
  }
}