带有正则表达式的文本字段的电话掩码

新手上路,请多包涵

我正在使用此功能来拨打电话面具并且几乎完美地工作。

 function mask(o, f)
{
    v_obj = o;
    v_fun = f;
    setTimeout("execmask()", 1)
};

function execmask()
{
    v_obj.value = v_fun(v_obj.value)
};

function mphone(v){
    v=v.replace(/\D/g,"");
    v=v.substring(0, 11);
    v=v.replace(/^(\d{2})(\d)/g,"(OXX$1) $2");
    v=v.replace(/(\d)(\d{4})$/,"$1-$2");
    return v;
}

在这里,我在文本字段中运行掩码:

 <input type="text" id="phone" name="phone" onkeypress="mask(this, mphone);" onblur="mask(this, mphone);" />

问题是我需要将这部分代码 (OXX$1) 更改为 (0XX$1)

现在的情况:

位数输入字段9位(OXX99) 99999-9999 8位(OXX99) 9999-9999

我需要的正确格式:

位数输入字段9位(0XX99) 99999-9999 8位(0XX99) 9999-9999

8 位或 9 位数字的数量由用户选择。

O 更改为 0 会导致掩码出错。

原文由 Danilo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 310
2 个回答
function mask(o, f) {
    setTimeout(function () {
        var v = f(o.value);
        if (v != o.value) {
            o.value = v;
        }
    }, 1);
}

function mphone(v) {
    var r = v.replace(/\D/g,"");
    r = r.replace(/^0/,"");
    if (r.length > 10) {
        // 11+ digits. Format as 5+4.
        r = r.replace(/^(\d\d)(\d{5})(\d{4}).*/,"(0XX$1) $2-$3");
    }
    else if (r.length > 5) {
        // 6..10 digits. Format as 4+4
        r = r.replace(/^(\d\d)(\d{4})(\d{0,4}).*/,"(0XX$1) $2-$3");
    }
    else if (r.length > 2) {
        // 3..5 digits. Add (0XX..)
        r = r.replace(/^(\d\d)(\d{0,5})/,"(0XX$1) $2");
    }
    else {
        // 0..2 digits. Just add (0XX
        r = r.replace(/^(\d*)/, "(0XX$1");
    }
    return r;
}

http://jsfiddle.net/BBeWN/

原文由 Markus Jarderot 发布,翻译遵循 CC BY-SA 3.0 许可协议

在这个项目中,您可以看到下面几种方法的使用,包括电话掩码并将它们应用于输入:

存储库: 反应文本字段掩码

演示沙箱: https ://codesandbox.io/s/eager-monad-qzod32

正则表达式掩码:


// (00) 00000-0000
const phoneMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '($1) $2')
    .replace(/(\d{5})(\d{4})/, '$1-$2');
};

// (00) 0000-0000
const landlineTelephoneMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '($1) $2')
    .replace(/(\d{4})(\d{4})/, '$1-$2');
};

// 10.000,00 -> 10000.00
const removeMoneyMask = (value: string | number) => {
  const originalNumber = Number(value);
  const numberIsWithMask = Number.isNaN(originalNumber);

  if (numberIsWithMask) {
    const stringValue = value.toString();
    const splitedMoneyMask = stringValue
      .split('.')
      .join('')
      .split(',')
      .join('.');

    return splitedMoneyMask.replace(/[^0-9.-]+/g, '');
  }

  return value.toString();
};

type BehaviorMode = 'standard' | 'typing';

const moneyMaskCustomization = {
  /**
   * typingMode - The value is typed from right to left:
   *  - '1' -> '0.01'
   *  - '10' -> '0.10'
   *
   * defaultMode - Simple conversion:
   *  - '1' -> '1.00'
   *  - '10' -> '10.00'
   */
  maskBehaviorMode: (behaviorMode: BehaviorMode, value: string | number) => {
    const numberWithoutMask = removeMoneyMask(value);
    const normalizedMoneyValue = moneyMaskCustomization.normalizeMoneyValue(
      numberWithoutMask.toString(),
    );
    const integerWithoutDecimalPlaces = normalizedMoneyValue.length === 1;

    if (behaviorMode === 'typing' && integerWithoutDecimalPlaces) {
      const newNumberFormat = Number(normalizedMoneyValue) / 100;
      return Number(newNumberFormat).toFixed(2);
    }

    if (behaviorMode === 'standard' && integerWithoutDecimalPlaces) {
      return Number(normalizedMoneyValue).toFixed(2);
    }

    return normalizedMoneyValue;
  },
  normalizeMoneyValue: (numberToNormalized: string) => {
    const [stringInteger, stringDecimal] = numberToNormalized.split('.');

    if (stringDecimal && stringDecimal.length === 1) {
      const lastPositionOfTheInteger = stringInteger.length - 1;
      const lastToIntegerPlace = stringInteger[lastPositionOfTheInteger];

      if (lastPositionOfTheInteger !== 0) {
        const firstIntegerPlace = stringInteger.substring(
          0,
          lastPositionOfTheInteger,
        );

        return `${firstIntegerPlace}.${lastToIntegerPlace}${stringDecimal}`;
      }

      return `${0}.${lastToIntegerPlace}${stringDecimal}`;
    }

    if (stringDecimal && stringDecimal.length === 3) {
      const firstDecimalPlace = stringDecimal.substring(0, 1);
      const lastTwoDecimalPlaces = stringDecimal.substring(1, 3);
      const integerIsZero = Number(stringInteger) === 0;

      if (integerIsZero) {
        return `${firstDecimalPlace}.${lastTwoDecimalPlaces}`;
      }

      return `${stringInteger}${firstDecimalPlace}.${lastTwoDecimalPlaces}`;
    }

    return numberToNormalized;
  },
};

// 10.000,00
const moneyMask = (
  value: string | number,
  maskBehaviorMode: BehaviorMode = 'standard',
) => {
  if (value || Number.isInteger(value)) {
    const moneyValue = moneyMaskCustomization.maskBehaviorMode(
      maskBehaviorMode,
      value,
    );

    return moneyValue
      .replace(/\D/g, '')
      .replace(/\D/g, '.')
      .replace(/(\d)(\d{2})$/, '$1,$2')
      .replace(/(?=(\d{3})+(\D))\B/g, '.');
  }
  return '';
};

// 000.000.000-00
const cpfMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue
    .replace(/\D/g, '')
    .replace(/(\d{3})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d{1,2})/, '$1-$2')
    .replace(/(-\d{2})\d+?$/, '$1');
};

// 00.000.000/0000-000
const cnpjMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d)/, '$1.$2')
    .replace(/(\d{3})(\d)/, '$1/$2')
    .replace(/(\d{4})(\d{2})/, '$1-$2');
};

// 000.000.000-00 or 00.000.000/0000-000
const cpfOrCnpjMask = (value: string | number) => {
  const stringValue = value.toString();
  if (stringValue.length >= 15) {
    return cnpjMask(value);
  }
  return cpfMask(value);
};

// 00000-000
const cepMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue.replace(/\D/g, '').replace(/^(\d{5})(\d{3})+?$/, '$1-$2');
};

// 00/00/0000
const dateMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue
    .replace(/\D/g, '')
    .replace(/(\d{2})(\d)/, '$1/$2')
    .replace(/(\d{2})(\d)/, '$1/$2')
    .replace(/(\d{4})(\d)/, '$1');
};

const onlyLettersMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue.replace(/[0-9!@#¨$%^&*)(+=._-]+/g, '');
};

const onlyNumbersMask = (value: string | number) => {
  const stringValue = value.toString();
  return stringValue.replace(/\D/g, '');
};

原文由 Marcos Santos Dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题