0

I want to restrict what characters a user can type in an input text field such that they can only type in numbers and periods and colons. So if they type anything else, it won't show up or register. This is for IP addresses for example: 10.200.66.106:8888

How can I achieve this in jQuery?

I've written a little example in jsFiddle: http://jsfiddle.net/6xMxs/

HTML:

<div id="outer">
    <div id="inner">
            <p>IP Address:</p>
        <p class="edit">2323</p>
    </div>
<div>

jQuery:

 $(document).ready(function() {
 $('.edit').editable('ipaddress/update',{ 
     type      : 'textarea',
     cancel    : 'Cancel',
     submit    : 'OK',        
     tooltip   : 'Click to edit...'
 });

});

Johnathan Au
  • 5,244
  • 18
  • 70
  • 128
  • possible duplicate of [java regex matching ip address and port number as captured groups](http://stackoverflow.com/questions/2908740/java-regex-matching-ip-address-and-port-number-as-captured-groups) – emerson.marini Oct 02 '13 at 10:04
  • _"and semicolons...for example: 10.200.66.106:8888"_ - So you mean colons, not semicolons? – nnnnnn Oct 02 '13 at 10:28

2 Answers2

1

You could remove not-allowed characters:

<input id="ip" type="text" />



$(document).ready(function() {

     $('#ip').keyup(function() { 
        var el = $(this),
            val = el.val();

         el.val(val.replace(/[^\d\.]/gi, ""));
     }).blur(function() {
         $(this).keyup();
     });
 });

Working fiddle

But there are better ways, you can for example completely "block" the entering of unwanted characters. And remember, you can easily avoid these restrictions when no server-side validation is being done.

Also, you might want to checkout the html5 attribute pattern which, as the context suggests, only works for html5 browsers.

Alex
  • 9,911
  • 5
  • 33
  • 52
0

You can use jquery's alphanumeric plugin to do that. Add some class to your element.

$(".myclass").numeric({allow:"."});
sudhansu63
  • 6,025
  • 4
  • 39
  • 52
  • 1
    Note that the alphanumeric plugin that you link to doesn't really work. That is, it does not stop the user from entering invalid characters via clipboard paste or drag'n'drop. – nnnnnn Oct 02 '13 at 10:27
  • i'm using the plugin right now and it just restricts the user from copying and pasting – Johnathan Au Oct 02 '13 at 10:56
  • @JohnathanAu - it doesn't restrict pasting, it just disables the context menu, so you can still paste via the Edit menu or keyboard. – nnnnnn Oct 02 '13 at 22:34