最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mobile number masking in React - Stack Overflow

programmeradmin0浏览0评论

Hi need to masked mobile number when user enter the mobile number in input box it should be 021 121 4544 in this format. means there should be 021{auto space}121{auto space}4544 how can i build in react this functionality?

class NumberCheck extends Component {
    state = {
        disabled: true,
        errorBlock: 'none',
        mobileNumber: '',
        error: ''
    };

handleOnChange = (event) => {
    let disabled = event.target.value ? disabled = false : disabled = true;
    this.setState({
        disabled: disabled,
        mobileNumber: event.target.value
    })
}

submit = (e) => {
    e.preventDefault();
    if (this.state.mobileNumber.match(/^02[0-9]{6,11}$/)) {
        this.setState({
            errorBlock: 'none'
        })
        const payload = {
            msisdn: this.state.mobileNumber
        }
        this.props.checkNumber(payload);
    } else {
        this.setState({
            error: ' Please enter valid mobile no',
            errorBlock: 'block'
        })

    }

}

render() {
    const { isLoading, isError } = this.props;
    if (isLoading) {
        return <Spinner />
    }
    if (isError) {
        return <ChangePlanError />
    }
    return (
        <form className="spring spring--sm">
            <p className="heading heading--3 heading--center no-gutter--top">{"Already with Vodafone?"}</p>
            <p className="heading--center">{"Sign in using a TXT code to check if you are eligible to upgrade or change your plan"}</p>
            <div className="alert alert--light alert--warning alert--arrow validation__warning" style={{ display: this.state.errorBlock }}>
                <div className="caption">
                    < div className="caption__media caption__media--top alert__media" >
                        <svg className="icon icon--extra-small icon--inherited" data-vft="icon-modifiers">
                            <use xmlnsXlink="" xlinkHref="#icon-block" />
                        </svg>
                    </div>
                    <div className="caption__text caption__text--top alert__text">
                        {this.state.error}
                    </div>
                </div>
            </div>
            <input
                type="text"
                onChange={this.handleOnChange}
                className="form__input form__input--dark"
                name="mobileno"
                placeholder="021 1234567"
                mask="000 000 0000" />
            <div id="submit" className="form__row form__row--medium gutter--bottom">
                <input
                    type="submit"
                    className={`button button--primary button--primary--grey button--full-width ${this.state.disabled ? 'button--disabled' : ''}`}
                    value=" Continue"
                    onClick={this.submit} />
            </div>
        </form >
    );
}

}

Hi need to masked mobile number when user enter the mobile number in input box it should be 021 121 4544 in this format. means there should be 021{auto space}121{auto space}4544 how can i build in react this functionality?

class NumberCheck extends Component {
    state = {
        disabled: true,
        errorBlock: 'none',
        mobileNumber: '',
        error: ''
    };

handleOnChange = (event) => {
    let disabled = event.target.value ? disabled = false : disabled = true;
    this.setState({
        disabled: disabled,
        mobileNumber: event.target.value
    })
}

submit = (e) => {
    e.preventDefault();
    if (this.state.mobileNumber.match(/^02[0-9]{6,11}$/)) {
        this.setState({
            errorBlock: 'none'
        })
        const payload = {
            msisdn: this.state.mobileNumber
        }
        this.props.checkNumber(payload);
    } else {
        this.setState({
            error: ' Please enter valid mobile no',
            errorBlock: 'block'
        })

    }

}

render() {
    const { isLoading, isError } = this.props;
    if (isLoading) {
        return <Spinner />
    }
    if (isError) {
        return <ChangePlanError />
    }
    return (
        <form className="spring spring--sm">
            <p className="heading heading--3 heading--center no-gutter--top">{"Already with Vodafone?"}</p>
            <p className="heading--center">{"Sign in using a TXT code to check if you are eligible to upgrade or change your plan"}</p>
            <div className="alert alert--light alert--warning alert--arrow validation__warning" style={{ display: this.state.errorBlock }}>
                <div className="caption">
                    < div className="caption__media caption__media--top alert__media" >
                        <svg className="icon icon--extra-small icon--inherited" data-vft="icon-modifiers">
                            <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#icon-block" />
                        </svg>
                    </div>
                    <div className="caption__text caption__text--top alert__text">
                        {this.state.error}
                    </div>
                </div>
            </div>
            <input
                type="text"
                onChange={this.handleOnChange}
                className="form__input form__input--dark"
                name="mobileno"
                placeholder="021 1234567"
                mask="000 000 0000" />
            <div id="submit" className="form__row form__row--medium gutter--bottom">
                <input
                    type="submit"
                    className={`button button--primary button--primary--grey button--full-width ${this.state.disabled ? 'button--disabled' : ''}`}
                    value=" Continue"
                    onClick={this.submit} />
            </div>
        </form >
    );
}

}

Share Improve this question edited Apr 15, 2019 at 5:09 Lazar Nikolic 4,3941 gold badge25 silver badges46 bronze badges asked Apr 15, 2019 at 4:58 Sushant SangleSushant Sangle 531 gold badge1 silver badge4 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

You can create a new string with previous string and replace it in the input.

const number = '0211214544';
const num = `${number.substring(0, 3)} ${number.substring(3, 6)} ${number.substring(6, number.length)}`;

console.log(num);

Created a working example in React.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: ''
    };
  }

  change = (event) => {
    let val = event.target.value;
    val = val.replace(/ /gm, '');
    console.log(val);

    let num = `${val.substring(0, 3)} ${val.substring(3, 6)} ${val.substring(6, val.length)}`;

    num = num.trim();

    this.setState({
      name: num
    });
  };

  render() {
    return (
      <div className="App">
        <input
          ref="inputName"
          value={this.state.name}
          onChange={this.change}
        />
      </div>
    );
  }
}

export default App;

The below function will mask the phone number , the basic operation to perform such functions is slicing/sub string and string concatenation

maskingFunction= (phoneNumber)=>{
  let subNum = phoneNumber.toString().substring(0,3)
   subNum = subNum + "XXXXXXXXXXXX"
   return subNum
}

I created a package that exposes an input component that displays a masked value according to the mask it receives.

The mask will change keeping the cursor at the correct position (even if you change part of the value in the middle of the input, paste some characters, or delete a part of it, and even if the mask changes).

You can see a Demo with examples at:

https://lucasbasquerotto.github.io/react-masked-input

(The first example has an input with a similar mask asked in this SO question, you only need to change the mask string to 999 999 9999).

To install the package: npm i react-hook-mask

Use it:

import { MaskedInput, createDefaultMaskGenerator } from 'react-hook-mask';

const maskGenerator = createDefaultMaskGenerator('999 999 9999');

const MobileNumberMaskedInput = () => {
    const [value, setValue] = React.useState('');

    return (
        <MaskedInput
            maskGenerator={maskGenerator}
            value={value}
            onChange={setValue}
        />
    );
};

This component wraps a default input, but the package also expose hooks to make you able to use it with any kind of component.

The function createDefaultMaskGenerator is convenient when all you need is to use a mask defined by a static string. You can also use dynamic masks that change according to the value, and even transforming the value (for example, making the characters uppercase).

The hook useMask is a generic hook that can be used with any component (even native components) as long as the component has a way to retrieve and to modify the cursor position.

The hook useRefMask wraps useMask and provides an easy way to forward a ref to the component, as well as using the ref element in the functions that manage the cursor position (Example).

The (more specific) hook useWebMask wraps useRefMask and can be used with any custom react-dom component that wraps an input and whose ref is an HTMLInputElement, without having to define a getter and a setter for the cursor position, and with an onChange function that sets the value received from the event object (Example).

发布评论

评论列表(0)

  1. 暂无评论