'Allow only numbers and multiple dots in jquery form input

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.



Solution 1:[1]

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");
        }
});

Solution 2:[2]

<input onKeyPress={(event) => { if (!/[0-9.]/.test(event.key)) { event.preventDefault(); } }}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amit Nandan Periyapatna
Solution 2 Alhassan Moro