[英]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". 由于某些原因,如果我只有“ 232 elm”,则下面的JavaScript总是显示特殊字符事件。
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: 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: 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 演示: 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! 这是stackoverflow的原始资源,它的输入用于停止除nubers之外的任何东西,我对此做了一些修改,希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.