ReactJS中的电话号码格式(xxx)xxx-xxxx onChange事件

时间:2019-05-09 08:03:00

标签: reactjs

我想为电话号码设置自定义格式。 例如ReactJS中的“(xxx)xxx-xxxx” onChange事件

2 个答案:

答案 0 :(得分:0)

class InputFormat extends Component {
  constructor(props) {
    super(props);
    this.state = {
      number: '',
    }
  }

  handleChange(value) {
    const input = value.replace(/\D/g, '').substring(0, 10);

    // Divide numbers in 3 parts :"(123) 456-7890" 
    const first = input.substring(0, 3);
    const middle = input.substring(3, 6);
    const last = input.substring(6, 10);

    if (input.length > 6) {
      this.setState({ number: `(${first}) ${middle}-${last}` })
    }
    else if (input.length > 3) {
      this.setState({ number: `(${first}) ${middle}` })
    }
    else if (input.length >= 0) {
      this.setState({ number: input })
    }
  }

  render() {
    return (
      <center className='input-format'>
        <Input
          placeholder='Enter number'
          value={this.state.number}
          onChange={(e) => this.handleChange(e.target.value)}
        />
      </center>
    );
  }
}

答案 1 :(得分:0)

我们可以使用此代码设置电话号码的格式,希望对您有所帮助。

 import * as Validations from '../../../validations/CommonValidations'; 
    export const phoneNumberValidation = function(value){
           let input = value.replace(/\D/g,'');
            input = input.substring(0,10);
            var size = input.length;
              if(size == 0){
                      input = input;
               }else if(size < 4){
                     input = '('+input;
               }else if(size < 7){
                       input = '('+input.substring(0,3)+') '+input.substring(3,6);
               }else{
                       input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - 
                    '+input.substring(6,10);
               }
               return input;
        }



    handleChange=(name,event,value)=>{
             let phoneValid =  Validations.phoneNumberValidation(val);
              this.setState({phone: Validations.isValidPhone(phoneValid)})

       }

     <TextField floatingLabelText={this.getMandatoryDetails("Mobile")} autoComplete="off" maxLength="16" value={this.state.phone || ""} onChange={this.handleChange.bind(this, 'phone')} />