简体   繁体   中英

How can I restrict input to only periods, numbers and semicolons in jQuery?

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...'
 });

});

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

$(".myclass").numeric({allow:"."});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM