javascript用户输入中的正则表达式



我在javascript中使用正则表达式时遇到问题。我想做的是一个表单注册,我必须在其中验证名字,所以我决定使用javascript验证(你能告诉我使用js是更好的选择还是使用ajax php-reg验证吗?(。所以我通过查看一些教程和从谷歌上阅读来编写代码,但我仍然有问题。它不起作用!它使用jquery在blur事件上运行,所以我需要你的帮助。我试图检查的模式是用户输入中的特殊字符/[\'^£$%&*((}{@#~?><>,|=_+]+$/g;

这是我的脚本:

$(document).on('blur','.first_name_input', function() {
var firstNameInput = $(".first_name_input").val();
if (firstNameInput !== '') {
//var exp = /[a-zA-Z0-9-]+$/g;
var exp = /['^£$%&*()}{@#~?><>,|=_+]+$/g;
//if (firstNameInput.test(/^['^£$%&*()}{@#~?><>,|=_+-]+$/)) {
//if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
if (firstNameInput.match(exp)) {
var firstnameValidity = "<div class='name_not_valid_div'>&times; Not allowed characters present!</div>";
$('body').prepend(firstnameValidity);
$(".name_not_valid_div").hide().fadeIn('slow');
if (!errorArray.includes("firstName")){
errorArray.push("firstName");
}
} else {
$(".name_not_valid_div").hide();
if (errorArray.includes("firstName")){
for(var i = errorArray.length - 1; i >= 0; i--) {
if(errorArray[i] === "firstName") {
errorArray.splice(i, 1);
}
}
}
}
}
});

我的html代码是:

<tr>
<td class="label">First Name: </td>
<td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
</tr>

1st:使用.trim()来避免左/右空白,甚至避免没有任何字符的空间$(".first_name_input").val().trim();

第二:用于验证

// if the string has special characters
function string_has_spec_char(str){
var reg = /[~`!#@$%^&*+=-[]\';,_./{}()|\":<>?]/g;
return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
var reg = /s/g;
return reg.test(str);
}

并像一样使用它

if(string_has_spec_char(firstNameInput) === false){
// the first name doesn't have special characters
}
if(string_has_spaces(firstNameInput) === false){
// the first name doesn't have spaces
}

相关内容

最新更新