如何在使用jquery提交表单时仅允许键盘字符
如果文本字段包含除键盘特殊字符以外的字符,如ascii字符表单127-255和iso-8859-1字符,如何在提交表单时使用jquery验证文本字段以显示警告消息 示例代码:如何在使用jquery提交表单时仅允许键盘字符,jquery,html,Jquery,Html,如果文本字段包含除键盘特殊字符以外的字符,如ascii字符表单127-255和iso-8859-1字符,如何在提交表单时使用jquery验证文本字段以显示警告消息 示例代码: <script type="text/javascript"> $(function() { $('#send').click(function() { var firstname=$('#firstname').va
<script type="text/javascript">
$(function()
{
$('#send').click(function()
{
var firstname=$('#firstname').val();
var pattern = "^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$";
if((!firstname.match(pattern)))
{
alert('your input contained not supported characters');
return false;
}
return true;
});
});
</script>
<form id="ajax_form" action="ajaxoutput.php">
<input type="text" name="FirstName" id="firstname" placeholder="FirstName" /><br>
<input type="text" name="LastName" placeholder="LastName" /><br>
<input type="file" name="image"/><br/>
<input type="submit" value="submit" name="submit" id="send" /> <input type="reset" value="reset"/>
</form>
Javascript代码:
<script type="text/javascript">
$(function()
{
$('#send').click(function()
{
var firstname=$('#firstname').val();
var pattern = "^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$";
if((!firstname.match(pattern)))
{
alert('your input contained not supported characters');
return false;
}
return true;
});
});
</script>
<form id="ajax_form" action="ajaxoutput.php">
<input type="text" name="FirstName" id="firstname" placeholder="FirstName" /><br>
<input type="text" name="LastName" placeholder="LastName" /><br>
<input type="file" name="image"/><br/>
<input type="submit" value="submit" name="submit" id="send" /> <input type="reset" value="reset"/>
</form>
$(函数()
{
$(“#发送”)。单击(函数()
{
var firstname=$('#firstname').val();
var pattern=“^[a-zA-Z0-9~`!@$%^&*(),.?\/']+$”;
如果((!firstname.match(pattern)))
{
警报(“您的输入包含不支持的字符”);
返回false;
}
返回true;
});
});
Html代码:
<script type="text/javascript">
$(function()
{
$('#send').click(function()
{
var firstname=$('#firstname').val();
var pattern = "^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$";
if((!firstname.match(pattern)))
{
alert('your input contained not supported characters');
return false;
}
return true;
});
});
</script>
<form id="ajax_form" action="ajaxoutput.php">
<input type="text" name="FirstName" id="firstname" placeholder="FirstName" /><br>
<input type="text" name="LastName" placeholder="LastName" /><br>
<input type="file" name="image"/><br/>
<input type="submit" value="submit" name="submit" id="send" /> <input type="reset" value="reset"/>
</form>
您将字符串作为.match()
参数传递,而该参数需要正则表达式
要创建regexp,可以执行以下操作:
var pattern = new RegExp("^[a-zA-Z0-9~`!@#$%^&*()_+-={}|:;<>,.?\/']+$");
var-pattern=newregexp(“^[a-zA-Z0-9~`.@$%^&*(),.?\/']+$”;
或
var模式=/^[a-zA-Z0-9~`!@$%^&*();
那比赛就成功了
因为你使用了很多特殊字符,你可能也需要转义其中的一些字符(使用
\
)。是的,我使用这个字符,但它只允许字母数字字符,如何允许键盘符号也只有一种方法,就是手动添加其中的每一个字符。我觉得“只有键盘字符”是不精确的,但我想你想说的是只有欧洲(或者可能是美国)的键盘字符我的键盘上有所有的字符,但是如何允许像上面代码中的[]\这样的特殊carachter如果我没有被误用,你需要像这样逃逸:\\\[\]
必须逃逸
,而且可能是*、+、美元和^。最好试试看,看看你是否需要逃离他们