我有脚本:
<script>
jQuery(document).ready(function($) {
var firstname = "/^[A-Za-z]+$/";
var email = /^[ ]*([^@@\s]+)@@((?:[-a-z0-9]+\.)+[a-z]{2,})[ ]*$/i;
jQuery('input#firstname').bind('input propertychange', function() {
if (firstname.test(jQuery(this).val())) {
jQuery(this).css({
'background': '#C2D699'
});
} else {
jQuery(this).css({
'background': '#FFC2C2'
});
}
});
jQuery('input#email').bind('input propertychange', function() {
if (email.test(jQuery(this).val())) {
jQuery(this).css({
'background': '#C2D699'
});
} else {
jQuery(this).css({
'background': '#FFC2C2'
});
}
});
});
</script>
并且在 View 中我的 View 中有两个文本框:
@Html.TextBoxFor(m => m.Register.FirstName, new { id = "firstname", @class = "form-control", @maxlength = "16" })
@Html.TextBoxFor(m => m.Register.Email, new { id = "email", @class = "form-control", @type = "email" })
电子邮件验证有效,但名字验证无效。我做错了什么?
最佳答案
您不需要在名字的 regex
两边加引号。
var firstname = "/^[A-Za-z]+$/"; // string
// ^ ^
用途:
var firstname = /^[A-Za-z]+$/; // `regex`
关于javascript - 使用 jQuery 在输入时验证表单输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30644551/