简体   繁体   中英

How to prevent all special characters in a form

So I am trying to prevent all special characters in a form. I want only numbers and alphabet characters. For some reason my javascript below is always shows special characters event if I have only "232 elm".

I also want to use a period or exlamation point. Mainly I am trying to prevent these ¡™£¢∞§¶•ªº. We have users that like to use the degree symbol instead of spelling "degree".

This code always shows the alert no matter what is typed?

var alphanumers = /^[a-zA-Z0-9]+$/;

if(!alphanumers.test($("#notes").val())){
   alert('You have special characters on instructions field.');
   e.preventDefault();
   return false;
}

This works for me:

HTML:

<h1>DEMO1</h1>
<input type="text" id="data" name="data" onkeyup="checkInput()">


<h1>DEMO2</h1>
<form action="#" method="post" onsubmit="return checkForm(this)">
 <input type="text" id="data2" name="data" value="123abc+-*/">
 <input type="submit">
</form>

Javascript:

DEMO1:
    function checkInput(){
        var testit = $('#data').val();
        if( /[^a-zA-Z0-9\-\/]/.test( testit ) ) {
           $('#data').css('background', '#f00');
        }else{
           $('#data').css('background', '#fff');
        }
    }

DEMO2:
    function checkForm( theForm ){
        var testit = $('#data2').val();
        if( /[^a-zA-Z0-9\-\/]/.test( testit ) ) {
           $('#data2').css('background', '#f00');
            return false;
        }else{
           $('#data2').css('background', '#fff');
            return true;
        }
    }

Demo: http://codesheet.org/codesheet/dMslCMmZ

I totally love this script! :

$("input").keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
         // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
         // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }
    // Ensure that it is a number or alphabet and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 90)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});

Here is the original source on stackoverflow , its for inputs to stop anything but nubers, i modified it a bit, hope it helps!

Try the jsfiddle

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