Levis Foster
Levis Foster

Reputation: 53

IP masking HTML input form with jQuery

So I need to validate an input field to accept IP addresses.

<form method="POST">
    <input type='text' placeholder='xxx.xxx.xxx.xxx' name='IP'>
</form>

Since there is no IP value for the attribute type, I would need to validate it using Javascript or some client-sided language. I've reached to this jQuery snippet using a mask library.

jQuery(function($){
   $("input").mask("9?99.9?99.9?99.9?99", {placeholder:" "});
});

This however doesn't work on my side. Here is how I include the scripts (just to point out).

<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="https://raw.githubusercontent.com/digitalBush/jquery.maskedinput/1.3.1/dist/jquery.maskedinput.js" type="text/javascript"></script>

Also, even if I manage to make this work, it still isn't the best option since two-digit parts of an IP address won't be rendered properly (i.e. 84.55.11.499). So my questions are:

  1. Why does the above code not work on my end but does on JSFiddle?
  2. How do I filter two-digit IP addresses with the mask library?

Upvotes: 3

Views: 35768

Answers (4)

Shahram
Shahram

Reputation: 25

this solution worked for me finely.

download this js file from : [https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js] or [https://github.com/shahram4m/blogfy/blob/main/static/js/jquery.inputmask.bundle.js] and reference it to your page. then using this Jquery code :

var ipv4_address = $('#ipInput');
ipv4_address.inputmask({
   alias: "ip",
   "placeholder": "_"
});

Upvotes: 0

Elham AM
Elham AM

Reputation: 365

I know this post is old, But I think the following code is the correct answer.

For Example:

<input type="text" class="form-input" id="ipv4" name="ipv4" placeholder="xxx.xxx.xxx.xxx"/>

Jquery code

var ipv4_address = $('#ipv4');
ipv4_address.inputmask({
   alias: "ip",
   "placeholder": "_"
});

This code in codepen

Upvotes: 0

I know is late, I know you need jQuery, but just in case you didn't knew it in HTML5 you can use pattern attribute with a regular expresion...

For example:

<input required pattern="^([0-9]{1,3}\.){3}[0-9]{1,3}$">

That regular expresion will validate IP addresses like:

xxx.xxx.xxx.xxx
x.x.x.x
xx.xx.xx.xx
x.xx.xxx.xx

Upvotes: 14

Scott Selby
Scott Selby

Reputation: 9580

I see you're already using a jQuery plugin - try this one that has a fully working IP mask

This plugin here

it's done like this:

 $('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});

or the identical - little shorter:

 $('.ip_address').mask('099.099.099.099');

the last example is the last line used in my fiddle example

according to the jQuery mask docs :

0: Only Numbers.

9: Only Numbers but optional.

so you see - 099.099.099.099, if you wanted to force 2 digits in between each decimal 009.009.009.009

Upvotes: 2

Related Questions