gpt4 book ai didi

Javascript 正则表达式表单验证

转载 作者:行者123 更新时间:2023-11-29 19:50:29 24 4
gpt4 key购买 nike

我有一个 HTML 表单,我想用正则表达式验证它。我将正则表达式包含在一个名为 emailRegex 的方法中,然后在 validateEmail 方法中调用该方法。当它尝试在 validateEmail 中调用我的 emailRegex 方法时出现错误。谁能告诉我我在这里做错了什么?

var validation={

emailRegex: function() {//new email Regular Expression for validateEmail method
return /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+ ([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/;
},

validateEmail: function(value) {

var regex = this.emailRegex;//takes value found in emailRegex

var offensiveWords = new RegExp(/\b(hate|notCool)b/); //offensive words regular expression

var email = document.getElementById("email");

var compactEmail = function(){//takes the value of the email form element and takes out any white spaces
var emailValue = email.value;
var compacted = emailValue.replace(" ","");
return compacted;
}

if(!regex.test(compactEmail())){//checks for a valid email address against regex from emailRegex method

alert("Please enter a valid email address");
email.focus();

return false;
}

if(!offensiveWords.test(compactEmail())){//checks for the offensive words found in offensiveWords regular expression.

alert("Your email address contains an offensive word");
email.focus();

return false;
}

return true;

}
}

最佳答案

我猜你看到了一个ReferenceError:

ReferenceError: emailRegex is not defined

您的变量 emailRegex 是一个函数,而不是一个属性。

你应该这样调用它:

var regex = this.emailRegex();

关于Javascript 正则表达式表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17938192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com