我有一个用于检查表单字段的 JavaScript。如果任何文本框中没有值,它的工作效果如何。但在文本框中填充值后,验证不起作用。下面是我的代码:
<script type="text/javascript">
function validate() {
debugger;
var val = "";
var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var name = document.getElementById('<%=txtname.ClientID %>').value;
var email = document.getElementById('<%=txtemail.ClientID %>').value;
var smtpport = document.getElementById('<%=txtsmtpport.ClientID %>').value;
var smtpsname = document.getElementById('<%= txtsname.ClientID %>').value;
var password = document.getElementById('<%=txtpassword.ClientID %>').value;
var confirmpass = document.getElementById('<%=txtconfirmpass.ClientID %>').value;
var secpassword = document.getElementById('<%=txtsecpassword.ClientID %>').value;
var confirmsecpass = document.getElementById('<%=txtconfirmsecpass.ClientID %>').value;
if (name == "") {
val += "Name not found \n";
}
if (email == "") {
val += "Email not found \n";
}
if (smtpport == "") {
val += "smtp port no not found \n";
}
if (smtpsname == "") {
val += "smtp server name not found \n";
}
if (password == "") {
val += "password not found \n";
}
if (confirmpass == "") {
val += "confirm password not found \n";
}
if (secpassword == "") {
val += "security password not found \n";
}
if (confirmsecpass == "") {
val += "confirm security password not found \n";
}
if (password != confirmpass) {
val += "Account Passwords do not match.\n";
}
if (secpassword != confirmsecpass) {
val += "Security Passwords do not match.\n";
}
if (email != "") {
var matchArray = emailPat.test(email);
if (matchArray) {
return true;
}
else {
val += "Not a valid e-mail address";
return false;
}
}
if (val.length > 0) {
alert(val);
return false
}
else {
return true;
}
}
</script>
这里是我如何在按钮单击时调用此脚本:
<asp:Button ID="btnSave" runat="server" CssClass="btn green" Text="Save" OnClientClick="return validate();" OnClick="btnSave_Click" />
我做错了什么,请帮帮我。
最佳答案
问题似乎出在下面的代码行
if (email != "") {
var matchArray = emailPat.test(email);
if (matchArray) {
return true;
}
else {
val += "Not a valid e-mail address";
return false;
}
}
如果电子邮件地址有效或电子邮件地址无效,您无需编写返回语句,因为下面的代码未执行,因为函数在电子邮件条件下有返回语句。
if (val.length > 0) {
alert(val);
return false
}
else {
return true;
}
尝试更改您的代码并从验证电子邮件条件中删除返回语句,您正在匹配有效电子邮件的正则表达式。
改变你的状况
if (email != "") {
var matchArray = emailPat.test(email);
if (matchArray) {
Consol.log('valid email');
}
else {
val += "Not a valid e-mail address";
}
}
关于填写表单数据后 Javascript 验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687461/