0
我使用JavaScript驗證驗證了我的表單,因爲整個驗證工作正常,但電子郵件驗證無效。我的表單代碼如下javascript電子郵件驗證不起作用
<form method="post" action="contact.php" name="myForm" onsubmit="return validateForm()">
<h3>To know more contact us today.</h3>
<table>
<tr>
<td>Name:
<br />
<input id="name" name="name" type="text" />
</td>
</tr>
<tr>
<td>Contact No:
<br />
<input id="contact" name="contact" type="text" />
</td>
</tr>
<tr>
<td>Email:
<br />
<input id="email" type="text" name="email" />
</td>
</tr>
<tr>
<td>Address:
<br />
<textarea cols="34" id="address" name="address" type="text"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
和我的javascript代碼如下
<script type="text/javascript">
function validateEmail() {
var emailID = document.["myForm"]["email"].value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
document.myForm.email.focus();
return false;
}
return (true);
}
function validateForm() {
var x = document.forms["myForm"]["name"].value;
if (x == null || x == "") {
alert("First name must be filled");
return false;
}
var x = document.forms["myForm"]["contact"].value;
if (x == null || x == "" || isNaN(document.myForm.contact.value) || document.myForm.contact.value.length != 10) {
alert("Contact Number Must be 10 Digits");
return false;
}
var x = document.forms["myForm"]["email"].value;
if (x == null || x == "") {
alert("Email is must");
return false;
}
else {
var ret = validateEmail();
if (ret == false) {
return false;
}
}
var x = document.forms["myForm"]["address"].value;
if (x == null || x == "") {
alert("Address cannot be empty");
return false;
}
return (true);
}
</script>
首先驗證邏輯不好。你有沒有聽說過regEx? –
你會得到什麼樣的錯誤 –
*有些人遇到問題時會想:「我知道,我會用正則表達式。」現在他們有兩個問題。* - [傑米Zawinski](http://en.wikiquote.org/wiki/Jamie_Zawinski) – Quentin