minus.273
minus.273

Reputation: 777

Material UI specific Textfield validation unexpected behaviour

Running a project on Node and having the front-end on React also to set the .env variables, I have built it with Material UI and all of the TextFields supplied work as expected with their particular validation. Except a field that uses the same pattern like the others, it does not acquire any input or do any kind of validation. Could anyone guide me if I am missing something or how to approach this problem?

class Dashboard extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      // ...
      serviceHTTPSCa: "",
      serviceHTTPSCaError: ""
    }

    // ...

    this.handleChangeServiceHTTPSCa = this.handleChangeServiceHTTPSCa.bind(this);
  }

  handleChangeServiceHTTPSCa(event) {
    if (event.target.value.match(/^([a-z0-9_-]+).crt$/i)) {
      this.setState({
        serviceHTTPSCa: event.target.value,
        serviceHTTPSCaError: "",
      });
    } else {
      this.setState({
        serviceHTTPSCaError: "Invalid format!"
      });
    }
  }

  render() {
    return (
      <div>
        {/* some other markup */}
        <TextField
          hintText="Service https Ca..."
          fullWidth={true}
          value={this.state.serviceHTTPSCa}
          onChange={this.handleChangeServiceHTTPSCa}
          errorText={this.serviceHTTPSCaError}
          type="text"
        />
        {/* some other markup */}
      </div>
    );
  }
}

Upvotes: 1

Views: 4728

Answers (1)

Liam
Liam

Reputation: 6743

serviceHTTPSCaError state should return error message or false and errorText should be errorText={this.state.serviceHTTPSCaError}

I did an example to check the email address

handleChangeServiceHTTPSCa(event) {
  if (!event.target.value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
    this.setState({
      serviceHTTPSCa: event.target.value,
      serviceHTTPSCaError: 'Email address is not vaild',
    },()=>{
      if(this.state.serviceHTTPSCa === ''){ // check if the input is empty
        this.setState({ serviceHTTPSCaError: false})
      });
  } else {
    this.setState({ serviceHTTPSCa: event.target.value,serviceHTTPSCaError: false });
  }
}

In render return

 <TextField
            hintText="Email Address"
            fullWidth={true}
            value={this.state.serviceHTTPSCa}
            onChange={this.handleChangeServiceHTTPSCa}
            errorText={this.state.serviceHTTPSCaError}
            type="text"
          />

Upvotes: 2

Related Questions