<div id="root">
</div>
* { 
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  background-color: #1D1F20;
  color: white;
}

.container {
  width: 80%;
  margin: 100px auto;
  border: 1px solid orange;
  border-radius: 5px;
  padding: 20px;
  height: 200px;
  text-align: center;
}

.form-warning {
  color: red;
  margin-top: 10px;
}

p {
  margin: 10px;
}
function FormError(props) {
  if (props.isHidden) {return null;}
  return (
    <div className="form-warning">
        {props.errorMessage}
    </div>
  )
}

const validateInput = (checkingText) => {
    
    const regexp = /^\d{10,11}$/; 
    // regular expression - checking if phone number contains only 10 - 11 numbers
    
    if (regexp.exec(checkingText) !== null) {
            return {
                isInputValid: true,
                errorMessage: ''
            };
        } else {
            return {
                isInputValid: false,
                errorMessage: 'Số điện thoại phải có 10 - 11 chữ số.'
            };
        }
}

class App extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      isInputValid: true,
      errorMessage: ''
      }
  }
  
  handleInput = event => {
    const { value } = event.target;
    this.setState({value});
  }  
  
  handleInputValidation = event => {
    const { isInputValid, errorMessage } = validateInput(this.state.value);
    this.setState({
      isInputValid: isInputValid,
      errorMessage: errorMessage
    })
    
  }
  
  render() {
    return(
      <div className="container">
        <h1>Form Validatiion</h1>
        <p>HTML Form Event: <strong>onBlur</strong></p>
        <input
              type="text"
              name="phonenumber"
              className="input-field"
              placeholder="Số điện thoại"
              onChange={this.handleInput}
              onBlur={this.handleInputValidation}
              required />
       <FormError 
              isHidden={this.state.isInputValid} 
              errorMessage={this.state.errorMessage} />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js