在web形式中,我有多个字段,每个字段都有一些独特的验证,如电话和邮政编码只有数字,有些字段不允许特殊字符。那么如何验证每个字段呢?
现在我验证像
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 32 && (charCode < 48 || charCode > 57)||(charCode==32))
return false;
return true;
}
function isAlphaNumericKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)&& (charCode < 48 || charCode > 57))
return false;
return true;
}
和某些情况下我需要允许一些特殊字符,如
function isANhypenKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)&& (charCode < 48 || charCode > 57) && (charCode!=44) && (charCode!=45))
return false;
return true;
}
和HTML表单
<input type="text" name="zipcode" id="zipcode" onkeypress="return isNumberKey(event);"/>
<input type="text" name="shipname" id="shipname" onkeypress="return isANhypenKey(event);" />
如何减少我的JS代码。我可以得到任何JS库文件或JS函数可以解决这个问题吗?由于
您可以使用几个库。如果您想坚持使用纯JavaScript而不使用jQuery,那么您最好的选择可能是Validate JS。
如果你愿意使用jQuery,这里有大量的jQuery选项——这些通常都有更多的特性,而且看起来也更好看。你也可以使用基础框架内建的验证器——它叫做Abide,但它使用jQuery。
是的http://rickharrison.github.io/validate.js/最好的和简单的使用检查链接
你可以看看jQuery的验证插件-它非常有用,你也可以很容易地在表单中添加验证错误,这样用户就会知道它的输入有什么问题。
这可能是您正在寻找的答案,也可能不是,但也许您应该寻找解决方案需要更少的JavaScript:
在HTML5中,你可以使用模式指定输入应该接受的值的类型,你可以在这个mozilla页面上阅读这个问题的答案:HTML5表单模式/验证。
<input type="text" name="country_code" pattern="put a regex here that describes only valid input for your situations" title="Three letter country code">
请注意,并不是所有的浏览器(主要是Safari和旧的IE)目前都支持pattern属性。
另一件值得注意的事情是,如果在JavaScript代码中使用RegEx是首选的解决方案,则可能更可取。