Rusty
Rusty

Reputation: 4473

How to show error message using PhoneInput from react-phone-input-2 package?

I am using PhoneInput from react-phone-input-2 package. I was wondering if it has a built-in feature to show error message. using the isValid property, I have been able to show red border on input in case some issue occurs. But I am still unable to show error message below the field. I have used the defaultErrorMessage property but it doesn't gets displayed if error occurs.

Can someone kindly let me know that there is a built-in feature for showing error message or I'll have to create a custom HOC for it?

<PhoneInput
  country={'ca'}
  value={this.state.phone}
  name="phone"
  onBlur={this.handleValidation}
  onChange={phone => this.setState({ phone })}
  defaultErrorMessage="It doesn't works, why?"
  isValid={this.state.errors.phone? false : true}
  inputProps={{
      name: 'phone',
      required: true,
     }}
  />

Upvotes: 0

Views: 4675

Answers (1)

Jay P
Jay P

Reputation: 626

According to the docs, You must pass a function and return a string or bool like so

<PhoneInput
  country={'ca'}
  value={this.state.phone}
  name="phone"
  onBlur={this.handleValidation}
  onChange={phone => this.setState({ phone })}
  defaultErrorMessage="It doesn't works, why?"
  isValid={(value, country) => {
    if (value.match(/12345/)) {
        return 'Invalid value: '+value+', '+country.name;
    } else if (value.match(/1234/)) {
        return false;
    } else {
        return true;
    }
  }}
  inputProps={{
      name: 'phone',
      required: true,
     }}
  />

If you return false instead of a string from this function your default error message will show

Upvotes: 1

Related Questions