国际电话输入-RegExp占位符问题

时间:2019-02-13 19:24:14

标签: javascript jquery regex

如果从下拉列表中选择一个国家,您将看到该国家的数字模式在占位符示例中已格式化。问题是我当前的代码将数字显示为字符串9,并且每个模式都有大括号。

RegExp中删除var pattern时,将显示所需的占位符:

发件人:

pattern = telInput.attr("placeholder")
  .replace(new RegExp("[0-9]", "g"), "9")
  .replace(/([9]\d{0,10})/g, '{{$1}}');

收件人:

    pattern = telInput.attr("placeholder");

然后,占位符显示不带大括号的DEMO数字字符串,这是所需的行为。现在唯一的问题是,当我输入一个值时,将输入plaholder值作为输入。

如何更改代码,以使占位符显示数字的演示字符串(当pattern = telInput.attr("placeholder");时),并且当我键入密码时,输入的占位符值将被重置,而我输入的输入仍遵循该国家/地区的数字格式? >

var intlPhoneNumber = function intlPhoneNumber(countryCode) {
  // get the country data from the plugin
  var countryData = $.fn.intlTelInput.getCountryData();
  var telInput = $("#phone-number");
  var telInputLabel = telInput.parents(".form-group").find("label");
  var countryDropdown = $("#phone-number-country");
  var phonePrefix = $('.phone-number-prefix');
  var fullPhoneNumber = $('#phone-number-full');
  var errorMsg = $("#error-msg");
  var initCountry = countryCode || 'us';
  var pattern = '';

  //set initial pattern for formatting
  if (initCountry === 'us') {
    pattern = '({{999}}) {{999}}-{{9999}}';
  } else {
    // using as temp until formatting on init figured out
    pattern = '{{9999999999999999999999}}';
  }

  // reset function to reset error state on validation
  var reset = function reset() {
    telInput.attr("placeholder", pattern);
    telInput.removeClass("has-error");
    telInputLabel.removeClass("has-error");
    errorMsg.addClass("hidden-xs-up");
  };

  // populate the country dropdown with intl-tel-input countries data
  $.each(countryData, function(i, country) {
    countryDropdown.append($("<option></option>").attr("value", country.iso2).text(country.name));
  });

  // init plugin for formatting placeholders
  telInput.intlTelInput({
    allowDropdown: false,
    initialCountry: initCountry,
    utilsScript: "https://1cf5229636340d3e1dd5-0eccc4d82b7628eccb93a74a572fd3ee.ssl.cf1.rackcdn.com/testing/utils.js"
  });


  // set dropdowns initial value
  var initialCountry = telInput.intlTelInput("getSelectedCountryData").iso2;
  var dialCode = telInput.intlTelInput("getSelectedCountryData").dialCode;
  countryDropdown.val(initialCountry);
  phonePrefix.text("+" + dialCode);

  // init format
  telInput.formatter({
    'pattern': pattern
  });


  // delete intl-tel-input items that aren't needed
  $('.flag-container').remove();
  $('.intl-tel-input').replaceWith(function() {
    return $('#phone-number', this);
  });

  // set placeholder
  telInput.attr("placeholder", pattern);

  // on blur: validate
  telInput.blur(function() {
    // reset states
    reset();

    if ($.trim(telInput.val())) {
      // if number is not valid
      if (telInput.intlTelInput("isValidNumber")) {
        // set hidden input to dial code + inputted number
        fullPhoneNumber.val(telInput.intlTelInput("getSelectedCountryData").dialCode + telInput.val());
      } else {
        // set error states
        telInput.addClass("has-error");
        telInputLabel.addClass("has-error");
        errorMsg.removeClass("hidden-xs-up");
        //clear hidden input val
        fullPhoneNumber.val("");
      }
    }
  });

  // on keyup / change flag: reset
  telInput.on("keyup change", reset);

  // listen to the country dropdown for changes.
  // updates placeholder and prefix when changed
  countryDropdown.change(function() {
    // Update Placeholder via plugin - so we can get the example number + format
    telInput.intlTelInput("setCountry", $(this).val());
    // Update Dial Code Prefix
    dialCode = telInput.intlTelInput("getSelectedCountryData").dialCode;
    phonePrefix.text("+" + dialCode);
    // Use updated placeholder to define formatting pattern
    pattern = telInput.attr("placeholder").replace(new RegExp("[0-9]", "g"), "9").replace(/([9]\d{0,10})/g, '{{$1}}');
    // update formatter
    telInput.formatter().resetPattern(pattern);
    // clear telephone input to prevent validation errors
    telInput.val("");
    // update placeholder to specific
    telInput.attr("placeholder", pattern);
  });
};

// Testing for prepopulation. If country code not supplied: default = 'us'
// const initCountryCode = 'ca'; // uncomment to pass in as param
intlPhoneNumber();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/jaridmargolin/formatter.js/master/dist/jquery.formatter.min.js"></script>
<script src="https://1cf5229636340d3e1dd5-0eccc4d82b7628eccb93a74a572fd3ee.ssl.cf1.rackcdn.com/testing/intlTelInput.min.js"></script>
<script src="https://cdn.staticaly.com/gh/jaridmargolin/formatter.js/master/dist/jquery.formatter.min.js"></script>
<div class="form-group">

  <select class="form-control" id="phone-number-country" name="phone-number-country" autocomplete="off"></select>
</div>
<div class="form-group">
  <div class="phone-number">
    <div class="form-control phone-number-prefix"></div>
    <input class="form-control" id="phone-number" name="phone-number" type="tel" autocomplete="off">
    <input type="hidden" id="phone-number-full" name="phone-number-full" />
  </div>

1 个答案:

答案 0 :(得分:1)

在将其添加到占位符或将其更新到占位符之前,请删除其格式大括号。我们也可以使用正则表达式替换它:

pattern.replace(/{{(\d+)}}/gm, `$1`)

var intlPhoneNumber = function intlPhoneNumber(countryCode) {
  // get the country data from the plugin
  var countryData = $.fn.intlTelInput.getCountryData();
  var telInput = $("#phone-number");
  var telInputLabel = telInput.parents(".form-group").find("label");
  var countryDropdown = $("#phone-number-country");
  var phonePrefix = $('.phone-number-prefix');
  var fullPhoneNumber = $('#phone-number-full');
  var errorMsg = $("#error-msg");
  var initCountry = countryCode || 'us';
  var pattern = '';

  //set initial pattern for formatting
  if (initCountry === 'us') {
    pattern = '({{999}}) {{999}}-{{9999}}';
  } else {
    // using as temp until formatting on init figured out
    pattern = '{{9999999999999999999999}}';
  }

  // reset function to reset error state on validation
  var reset = function reset() {
    telInput.attr("placeholder", pattern.replace(/{{(\d+)}}/gm, `$1`));
    telInput.removeClass("has-error");
    telInputLabel.removeClass("has-error");
    errorMsg.addClass("hidden-xs-up");
  };

  // populate the country dropdown with intl-tel-input countries data
  $.each(countryData, function(i, country) {
    countryDropdown.append($("<option></option>").attr("value", country.iso2).text(country.name));
  });

  // init plugin for formatting placeholders
  telInput.intlTelInput({
    allowDropdown: false,
    initialCountry: initCountry,
    utilsScript: "https://1cf5229636340d3e1dd5-0eccc4d82b7628eccb93a74a572fd3ee.ssl.cf1.rackcdn.com/testing/utils.js"
  });


  // set dropdowns initial value
  var initialCountry = telInput.intlTelInput("getSelectedCountryData").iso2;
  var dialCode = telInput.intlTelInput("getSelectedCountryData").dialCode;
  countryDropdown.val(initialCountry);
  phonePrefix.text("+" + dialCode);

  // init format
  telInput.formatter({
    'pattern': pattern
  });


  // delete intl-tel-input items that aren't needed
  $('.flag-container').remove();
  $('.intl-tel-input').replaceWith(function() {
    return $('#phone-number', this);
  });

  // set placeholder
  telInput.attr("placeholder", pattern.replace(/{{(\d+)}}/gm, `$1`));

  // on blur: validate
  telInput.blur(function() {
    // reset states
    reset();

    if ($.trim(telInput.val())) {
      // if number is not valid
      if (telInput.intlTelInput("isValidNumber")) {
        // set hidden input to dial code + inputted number
        fullPhoneNumber.val(telInput.intlTelInput("getSelectedCountryData").dialCode + telInput.val());
      } else {
        // set error states
        telInput.addClass("has-error");
        telInputLabel.addClass("has-error");
        errorMsg.removeClass("hidden-xs-up");
        //clear hidden input val
        fullPhoneNumber.val("");
      }
    }
  });

  // on keyup / change flag: reset
  telInput.on("keyup change", reset);

  // listen to the country dropdown for changes.
  // updates placeholder and prefix when changed
  countryDropdown.change(function() {
    // Update Placeholder via plugin - so we can get the example number + format
    telInput.intlTelInput("setCountry", $(this).val());
    // Update Dial Code Prefix
    dialCode = telInput.intlTelInput("getSelectedCountryData").dialCode;
    phonePrefix.text("+" + dialCode);
    // Use updated placeholder to define formatting pattern
    pattern = telInput.attr("placeholder").replace(new RegExp("[0-9]", "g"), "9").replace(/([9]\d{0,10})/g, '{{$1}}');
    // update formatter
    telInput.formatter().resetPattern(pattern);
    // clear telephone input to prevent validation errors
    telInput.val("");
    // update placeholder to specific
    //telInput.attr("placeholder", pattern.replace(/{{(\d+)}}/gm, `$1`));
  });
};

// Testing for prepopulation. If country code not supplied: default = 'us'
// const initCountryCode = 'ca'; // uncomment to pass in as param
intlPhoneNumber();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/jaridmargolin/formatter.js/master/dist/jquery.formatter.min.js"></script>
<script src="https://1cf5229636340d3e1dd5-0eccc4d82b7628eccb93a74a572fd3ee.ssl.cf1.rackcdn.com/testing/intlTelInput.min.js"></script>
<script src="https://cdn.staticaly.com/gh/jaridmargolin/formatter.js/master/dist/jquery.formatter.min.js"></script>
<div class="form-group">

  <select class="form-control" id="phone-number-country" name="phone-number-country" autocomplete="off"></select>
</div>
<div class="form-group">
  <div class="phone-number">
    <div class="form-control phone-number-prefix"></div>
    <input class="form-control" id="phone-number" name="phone-number" type="tel" autocomplete="off">
    <input type="hidden" id="phone-number-full" name="phone-number-full" />
  </div>