我有一个用于检查表单字段的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" />
我对此有什么误解,请帮帮我。
答案 0 :(得分:1)
问题似乎与下面的代码行
if (email != "") {
var matchArray = emailPat.test(email);
if (matchArray) {
return true;
}
else {
val += "Not a valid e-mail address";
return false;
}
}
在此情况下,如果有效的电子邮件地址或无效的电子邮件地址,则无需编写return语句,因为您下面的代码未执行,因为函数处于电子邮件状态时具有return语句。
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";
}
}