0

I wanted to know a way to allow only numbers and multiple dots in using jquery in a form input.

The scenario is that the form input holds a version name and version name can have values like 6.0.2345 and as far as my research went, I could get only the numbers working by the following code:

$('.number').keydown(function(event) {
    if(event.which < 46
    || event.which > 59) {
        event.preventDefault();
    } // prevent if not number/do
});

But this allows only numbers and does not allow me to use backspace or delete. Any workaround from this method that I can use so that I can allow only multiple dots and numbers in the input file.

2 Answers2

0

Finally arrived at this answer which works.

$(".submit").on('click',function(e){
        e.preventDefault();
        var test_val = $(".test").val();
        var test_regex = /^(\*|\d+(\.\d+){0,3}(\.\*)?)$/i;
        if(!test_regex.test(test_val)){
            alert("This is not a valid entry");
        }
});
-1
<input onKeyPress={(event) => { if (!/[0-9.]/.test(event.key)) { event.preventDefault(); } }}
Ethan
  • 881
  • 8
  • 14
  • 26
Alhassan Moro
  • 77
  • 1
  • 1
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Apr 18 '22 at 17:07