【问题标题】:International Telephone Input - RegExp placeholder issues国际电话输入 - RegExp 占位符问题
【发布时间】:2019-02-13 19:24:14
【问题描述】:

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

当您从var pattern 中删除RegExp 时显示所需的占位符:

发件人:

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>

【问题讨论】:

    标签: javascript jquery regex


    【解决方案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>

    【讨论】:

    • 问题还在于新的国家/地区选择。如果您更改国家/地区,它会更改数字模式和占位符。如果您删除具有 RegExp 的 .replace,您可以看到占位符以所选国家/地区的模式显示演示编号。
    • 感谢@wp78de 默认占位符不是显示所有的 9,而是为每个模式提供一个演示编号。如果您删除 .replace() 上的 pattern = telInput.attr("placeholder").replace(new RegExp("[0-9]", "g"), "9").replace(/([9]\d{0,10})/g, '{{$1}}'); ,您可以看到这一点 我如何在不使用 9 作为占位符的情况下使该功能正常工作?删除.replace() 时显示的演示编号会很好
    • @KyleUnderhill 那么,您不想设置通用模式吗?然后,不要使用格式化程序模式更新它。更新。您可能确实为初始数字定义了一个固定值。
    猜你喜欢
    • 2021-01-29
    • 2020-05-28
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    相关资源
    最近更新 更多