我已经开始为用户注册编写验证。这个表单是用户可以在网站上注册的,但是我在如何正确地为每个字段编写验证方面遇到了问题。
到目前为止:
<div id="content">
<div class="ic"></div>
<div class="inner">
<div class="container_12">
<div class="wrapper">
<div class="grid_12">
</div>
</div>
<div class="wrapper">
<div class="grid_12">
<h2 class="h-pad1">Open an Account with Us</h2>
<form action="" id="validate" class="form" method="POST">
<fieldset>
<div class="formRow">
<label for="login">Username:</label>
<div class="loginInput"><input type="text" name="username" class="validate[required]" id="username" maxlength="15"/></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Password:</label>
<div class="loginInput"><input type="password" name="password" class="validate[required]" id="pass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Repeat Password:</label>
<div class="loginInput"><input type="password" name="rpassword" class="validate[required]" id="rpass" /></div>
<div class="clear"></div>
</div>
<div class="formRow">
<label for="pass">Email:</label>
<div class="loginInput"><input type="text" name="email" class="validate[required]" id="email" /></div>
<div class="clear"></div>
</div>
要添加的正确代码是什么?谢谢。
答案 0 :(得分:1)
如果您要使用常规JavaScript,最重要的任务是学习如何使用document.getElementById()。使用该功能,您可以获取不同字段中的值并检查存储在其中的内容。
我会有一个高级函数 validateRegistrationForm(),它调用函数来验证每个字段。例如
function validateRegistrationForm(){
if(!validateEmailField()) // Invalid email format
return;
if(!validatePasswordField()) // Invalid password length
return;
if(validateUserNameField()) // invalide characters in email
return;
.
.
etc.
}
function validateEmailField(){
var x=document.getElementById("email").value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
errorPopup("Not a valid e-mail address");
return false;
}
if(email==x) //If the old email is equal to the current then perform no check for uniqueness. On the server side the email portion will be ignored.
return true;
return isEmailUnique(); // return true if the email is unique
}
答案 1 :(得分:0)
您可以拥有以下内容:
function validate()
{
var uName = document.getElementById('username');
if(uName == '' or uName=' ')
{
// do something
}
repeat for other elements.
.
.
.
.
// in the end, you can return true; if all validation condition meet or else return false;
}