【发布时间】:2016-10-21 23:53:09
【问题描述】:
我想要一个表单,它要求输入用户的姓名、电话号码和电子邮件地址。姓名字段应仅包含字母,电话号码字段应仅包含数字,电子邮件字段应包含“@”。表单需要使用 Javascript 进行验证。验证应该在用户单击提交时进行。有人可以帮忙吗?请看我现有的代码:
HTML:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Contact</title>
<script src="datavalidation.js"></script>
</head>
<body onload="document.registration.userid.focus();">
<section>
<h1>Contact</h1></br>
<h2>To get in contact with us please fill out the contact form below</h2></br>
<p>Fill in all of the boxes below and click the 'Submit' button to submit message and one of our team will get back in touch with you within 48 hours</p></br>
<form name='registration' onSubmit="return formValidation();">
<ul>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="number">Phone No:</label></li>
<li><input type="text" name="number" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label for="desc">Message:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</section>
Javascript:
function formValidation()
{
var uname = document.registration.username;
var unumber = document.registration.number;
var uemail = document.registration.email;
{
if(allLetter(uname))
{
if(allnumeric(unumber))
{
if(ValidateEmail(uemail))
}
}
}
return false;
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function allnumeric(unumber)
{
var numbers = /^[0-9]+$/;
if(unumber.value.match(numbers))
{
return true;
}
else
{
alert('Phone number must have numeric characters only');
unumber.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
return false;
}
else
{
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
}
请帮忙!
【问题讨论】:
标签: javascript html validation