Using regex to restrict input in textbox [duplicate]

房东的猫 提交于 2021-02-08 10:44:20

问题


/^+{0,1}(?:\d\s?){11,13}$/ this regex allows + at first place only and numbers only...

on keypress I want user should only be able to type + at first and digits that what above regex validates But code always goes to if part..why regex not working in this scenario

function ValidatePhone(phone) {
            var expr = /^\+?(?:\d\s?){11,13}$/;
            return expr.test(phone);
        }


var countofPlus = 0;

    $("#phone").on("keypress", function (evt) {
        if (evt.key == "+")
        {
            countofPlus = countofPlus + 1;
            if (countofPlus > 1 || this.value.length >= 1) {
                return false;
            }
            else return true;
        }
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && charCode != 43 && charCode != 32 && charCode != 40 && charCode != 41 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    });
$("#phone").on("keyup", function (evt) {
        debugger;
        if (evt.key == "+") {
            countofPlus--;
            return true;
        }

    });

回答1:


Adapting an answer from HTML input that takes only numbers and the + symbol to your use-case yields the following (IE-)compatible code:

// Apply filter to all inputs with data-filter:
var inputs = document.querySelectorAll('input[data-filter]');

for (var i = 0; i < inputs.length; i++) {
  var input = inputs[i];
  var state = {
    value: input.value,
    start: input.selectionStart,
    end: input.selectionEnd,
    pattern: RegExp('^' + input.dataset.filter + '$')
  };
  
  input.addEventListener('input', function(event) {
    if (state.pattern.test(input.value)) {
      state.value = input.value;
    } else {
      input.value = state.value;
      input.setSelectionRange(state.start, state.end);
    }
  });

  input.addEventListener('keydown', function(event) {
    state.start = input.selectionStart;
    state.end = input.selectionEnd;
  });
}
<input id='tel' type='tel' data-filter='\+?\d{0,13}' placeholder='phone number'>

Above code takes copy & pasting, selecting, backspacing etc. into account where your current implementation fails.

Also, I modified the given regex to \+?\d{0,13} so it allows for incomplete input. Use HTML5 form validation to validate the final result.




回答2:


I think this regex is being applied only to the char code i.e. a string of length 1. In this case regex will always fail.

Instead, try running the regex test on the input value.



来源:https://stackoverflow.com/questions/44417888/using-regex-to-restrict-input-in-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!