JavaScript to accept only numbers between 0 to 255 range

后端 未结 8 1571
野趣味
野趣味 2021-01-22 13:14

My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is ente

8条回答
  •  一生所求
    2021-01-22 13:31

    Single Integer

    You can use the following solution to check if the user input for a single integer is between 0 - 255:

    document.getElementById('example').addEventListener('input', event => {
      const input = event.target.value;
      console.log(/^\d+$/.test(input) && input > -1 && input < 256);
    });


    IP Address

    Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:

    document.getElementById('example').addEventListener('input', event => {
      const input = event.target.value;
      console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
    });

提交回复
热议问题