问题描述
我正在研究表单验证脚本,并且遇到了一些困难。该表格旨在确保用户填写姓名,真实的电子邮件,类别(从他下拉)和一个问题:
这个名字表单并从表单收集所有数据:
< script>
函数checkForm(form1){
name = document.getElementById(FieldData0).value;
category = document.getElementById(FieldData3)。value;
question = document.getElementById(FieldData1)。value;
email = document.getElementById(FieldData2).value;
检查是否在名称字段中有内容。它工作正常,并验证完全是应该的,显示错误文本:
if(name ==){
hideAllErrors();
document.getElementById(nameError)。style.display =inline;
document.getElementById(FieldData0)。select();
document.getElementById(FieldData0)。focus();
返回false;
这也适用。它会检查电子邮件字段是否为空,如果电子邮件字段为空,则显示错误文本并选择该字段:
}其他if(email ==){
hideAllErrors();
document.getElementById(emailError)。style.display =inline;
document.getElementById(FieldData2)。select();
document.getElementById(FieldData2)。focus();
返回false;
}
这同样适用,确保问题字段不是' t空:
else if(question ==){
hideAllErrors();
document.getElementById(questionError)。style.display =inline;
document.getElementById(FieldData1)。select();
document.getElementById(FieldData1)。focus();
返回false;
}
这部分工作 - 如果没有选择下拉菜单,它将显示错误消息,但这并不会阻止表单提交,它只是在表单提交时显示错误文本:
else if(category ==){
hideAllErrors();
document.getElementById(categoryError)。style.display =inline;
document.getElementById(FieldData3)。select();
document.getElementById(FieldData3)。focus();
返回false;
}
无论我放在哪里,这个都不起作用。上周我在同一个脚本上使用了一个变体,它运行良好。这是应该检查,看看输入的电子邮件看起来像一个真正的电子邮件地址:
否则if(!check_email(document。 getElementById(FieldData1)。value)){
hideAllErrors();
document.getElementById(emailError2)。style.display =inline;
document.getElementById(FieldData2)。select();
document.getElementById(FieldData2)。focus();
返回false;
}
否则它让表单提交:
return true;
}
这会检查电子邮件:
函数check_email(e){
ok =1234567890qwertyuiop [] asdfghjklzxcvbnm。@ -_ QWERTYUIOPASDFGHJKLZXCVBNM; (i.o)(e.charAt(i))返回(false);
if(document.images){
re = /(@.*@)|(\.\.)|(^ \)|(^ @)|(@ $)|(\ $)|(@ \)/。。。
re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4 } | [0-9] {1,3})(\])$ /?;
if(!e.match(re)& e.match(re_two)){
return(-1);
}
}
}
此功能隐藏所有错误,使用户不会被红色文字轰炸。我尝试了放入document.getElementById(emailError)。style.display =none但是打破了整个事情:
function hideAllErrors(){
document.getElementById(nameError)。style.display =none
document.getElementById(emailError)。style.display =none
document.getElementById(categoryError)。style.display =none
document.getElementById(questionError)。style.display =none
}
< / script>
表单看起来像这样:
< form onSubmit =return checkForm(); method =postaction =http://www.emailmeform.com/fid.php?formid=303341io4uname =form1>
< div class = error id = nameError>必需:请输入您的名称< /强> < span>< / span>< br>< input type =textname =FieldData0id =FieldData0value =size =22tabindex =1/>
< label for =name>< / label>< / p>
< p>< div class = error id = emailError>必需:请输入您的电子邮件地址< br />< / div>
< div class = error id = nameError2>这看起来不像真正的电子邮件地址,请检查并重新输入< br />< / div>
< strong>< p>电子邮件:< / strong> < span>(不会发布)< / span>< br>< input type =textname =FieldData2id =FieldData2value =size =22tabindex =2 />
< label for =email>< / label>
< / p>
< div class = error id = categoryError>请从下拉菜单中选择一个类别< br>< / div>
< p>< strong>类别:< / strong> <跨度>< /跨度><峰; br>
< p>< select id =FieldData3name =FieldData3>
< option value =>请选择一个类别< / option>
< option value =a> a< / option>
< option value =b> b< / option>
< option value =c> c< / option>
< option value =d> d< / option>
< option value =e> e< / option>
< option value =f> f< / option>
< option value =other>其他< / option>
< / select>< label for =category>< / label>
< p>< div class = error id = questionError>请在下方输入您的问题:< br>< / div>< label for =question> < strong>< p>您的问题:< / strong> <跨度>< /跨度>< /标签><峰; br>
< p>< input type =submitclass =btnvalue =提交问题name =Submit>< / p>
< / div>
< / form>
问题是我运行检查的顺序?我似乎无法弄清楚这一点。任何帮助,将不胜感激。
我冒昧地重新编写您的JavaScript,使其更易读,更容易进行调试。
正如Marc Bernier所说,dropdown元素不支持 select
函数,所以我把 if
语句来防止异常。我还简化了你的 checkEmail
函数,它似乎相当复杂。为了使 checkForm
代码更简单,我将它重命名为 isAnInvalidEmail
。
您也错误地在HTML中命名了'emailError2' div
,这会导致javascript中出现另一个异常。你的HTML相当混乱,在某些情况下,它是无效的。缺少某些属性值和缺少结束标记的引号。您应该考虑使用,以确保您的HTML清晰并符合标准。
我在jsbin上托管了您的代码:进行编辑)
$ b $$ b
函数checkForm(){
hideAllErrors()
$ b
;
var formIsValid =
showErrorAndFocusIf('FieldData0',isEmpty,'nameError')
&& showErrorAndFocusIf('FieldData2',isEmpty,'emailError')
&& showErrorAndFocusIf('FieldData2',isAnInvalidEmail,'emailError2')
&& showErrorAndFocusIf('FieldData3',isEmpty,'categoryError')
&& showErrorAndFocusIf('FieldData1',isEmpty,'questionError');
/ *对于调试,可以防止表单提交。 * /
if(formIsValid){
alert(Valid form!);
返回false;
}
返回formIsValid;
函数showErrorAndFocusIf(fieldId,predicate,errorId){
var field = document.getElementById(fieldId);
if(predicate(field)){
document.getElementById(errorId).style.display ='inline';
if(field.select){
field.select();
}
field.focus();
返回false;
}
返回true;
}
函数isEmpty(field){
return field.value =='';
}
函数isAnInvalidEmail(field){
var email = field.value;
var ok =1234567890qwertyuiop [] asdfghjklzxcvbnm。@ -_ QWERTYUIOPASDFGHJKLZXCVBNM; (i = 0; i< email.length; i ++){
if(ok.indexOf(email.charAt(i))< 0){
返回true;
}
}
re = /(@.*@)|(\.\。)|(^ \。)|(^ @)|( @ $)|(\ $)|(@ \)/。
re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4 } | [0-9] {1,3})(\])$ /?;
返回re.test(email)|| !re_two.test(电子邮件);
$ b函数hideAllErrors(){
document.getElementById(nameError)。style.display =none
document.getElementById(emailError)。style.display =none
document.getElementById(emailError2)。style.display =none
document.getElementById(categoryError)。style .display =none
document.getElementById(questionError)。style.display =none
}
并清理HTML:
< form onSubmit =return checkForm() ; method =postaction =http://www.emailmeform.com/fid.php?formid=303341io4uname =form1>
< div>
< div class =errorid =nameError>
必填:请输入您的姓名
< / div>
< label for =FieldData0>< strong>名称:< / strong>< / label>
< input type =textname =FieldData0id =FieldData0value =size =22tabindex =1/>
< / div>
< div>
< div class =errorid =emailError>
必填项:请输入您的电子邮件地址
< / div>
< div class =errorid =emailError2>
这看起来不是真正的电子邮件地址,请检查并重新输入
< / div>
< label for =FieldData2>< strong>电子邮件:< / strong>(不会发布)< / label>
< input type =textname =FieldData2id =FieldData2value =size =22tabindex =2/>
< / div>
< div>
< div class =errorid =categoryError>
请从下拉菜单中选择一个类别
< / div>
< label for =FieldData3>< strong>类别:< / strong>< / label>
< select id =FieldData3name =FieldData3>
< option value =>请选择一个类别< / option>
< option value =a> a< / option>
< option value =b> b< / option>
< option value =c> c< / option>
< option value =d> d< / option>
< option value =e> e< / option>
< option value =f> f< / option>
< option value =other>其他< / option>
< / select>
< / div>
< div>
< div class =errorid =questionError>
请在下面的方框中输入您的问题:
< / div>
< label for =FieldData1>< strong>您的问题:< / strong>< / label>
< textarea name =FieldData1id =FieldData1cols =50rows =10>< / textarea>
< / div>
< input type =submitclass =btnvalue =Submit Questionname =Submit>
< / form>
I'm working on a form validation script at work and am having some difficulty. The form is meant to make sure that the user fills out a name, a real-looking email, a category (fromt he drop down) and a question:
This names the form and gathers all the data up from the form:
<script>
function checkForm(form1) {
name = document.getElementById("FieldData0").value;
category = document.getElementById("FieldData3").value;
question = document.getElementById("FieldData1").value;
email = document.getElementById("FieldData2").value;
This checks to see that something is in the "name" field. It works fine and validates exactly like it should, displaying the error text:
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("FieldData0").select();
document.getElementById("FieldData0").focus();
return false;
This also works just like it should. It checks to see if the email field is empty and if it is empty,displays error text and selects that field:
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
This also works just like it should, makes sure that the questions field isn't empty:
else if (question == "") {
hideAllErrors();
document.getElementById("questionError").style.display = "inline";
document.getElementById("FieldData1").select();
document.getElementById("FieldData1").focus();
return false;
}
This one works partially - If no drop down is selected, it will display the error message, but that doesn't stop the form from submitting, it just displays the error text while the form submits:
else if (category == "") {
hideAllErrors();
document.getElementById("categoryError").style.display = "inline";
document.getElementById("FieldData3").select();
document.getElementById("FieldData3").focus();
return false;
}
This one doesn't work at all no matter where I put it. I used a variation on the same script last week and it worked fine. This is supposed to check to see that the email entered looks like a real email address:
else if (!check_email(document.getElementById("FieldData1").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
Otherwise it lets the form submit:
return true;
}
This checks the email out:
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
This function hides all errors so the user isn't bombarded with red text. I tried putting in "document.getElementById("emailError").style.display = "none"" but that breaks the whole thing:
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
</script>
And the form looks like this:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<p><div class=error id=nameError>Required: Please enter your name<br/></div><p><strong>Name:</strong> <span></span><br><input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
<label for="name"></label></p>
<p><div class=error id=emailError>Required: Please enter your email address<br/></div>
<div class=error id=nameError2>This doesn't look like a real email address, please check and reenter<br/></div>
<strong><p>Email:</strong> <span>(will not be published)</span><br><input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
<label for="email"></label>
</p>
<div class=error id=categoryError>Please select a category from the drop-down menu<br></div>
<p><strong>Category:</strong> <span></span><br>
<p><select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select><label for="category"></label>
<p><div class=error id=questionError>Please type your question in the box below:<br></div><label for="question"><strong><p>Your Question:</strong> <span></span></label><br>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea></p>
<p><input type="submit" class="btn" value="Submit Question" name="Submit"></p>
</div>
</form>
Is the problem the order that I run the checks? I can't seem to figure this out. Any help would be appreciated.
I've taken the liberty to re-write your javascript to make it more readable and easier to debug.
As Marc Bernier mentioned, the dropdown element does not support the select
function so I put an if
statement around it to prevent an exception. I've also simplified your checkEmail
function, it seemed rather convoluted. I renamed it to isAnInvalidEmail
in order to make the checkForm
code simpler.
You have also incorrectly named the 'emailError2' div
in your HTML, which would cause another exception in the javascript. Your HTML is rather messy and, in some cases, invalid. There are missing quotes on some attribute values and missing end-tags. You should consider using the W3C validator to ensure your HTML is clean and is standards compliant.
I've hosted your code on jsbin: http://jsbin.com/iyeco (editable via http://jsbin.com/iyeco/edit)
Here's the cleaned up Javascript:
function checkForm() {
hideAllErrors();
var formIsValid =
showErrorAndFocusIf('FieldData0', isEmpty, 'nameError')
&& showErrorAndFocusIf('FieldData2', isEmpty, 'emailError')
&& showErrorAndFocusIf('FieldData2', isAnInvalidEmail, 'emailError2')
&& showErrorAndFocusIf('FieldData3', isEmpty, 'categoryError')
&& showErrorAndFocusIf('FieldData1', isEmpty, 'questionError');
/* For debugging, lets prevent the form from submitting. */
if (formIsValid) {
alert("Valid form!");
return false;
}
return formIsValid;
}
function showErrorAndFocusIf(fieldId, predicate, errorId) {
var field = document.getElementById(fieldId);
if (predicate(field)) {
document.getElementById(errorId).style.display = 'inline';
if (field.select) {
field.select();
}
field.focus();
return false;
}
return true;
}
function isEmpty(field) {
return field.value == '';
}
function isAnInvalidEmail(field) {
var email = field.value;
var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i = 0; i < email.length; i++){
if(ok.indexOf(email.charAt(i)) < 0) {
return true;
}
}
re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return re.test(email) || !re_two.test(email);
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("emailError2").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
And the cleaned up HTML:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<div>
<div class="error" id="nameError">
Required: Please enter your name
</div>
<label for="FieldData0"><strong>Name:</strong></label>
<input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
</div>
<div>
<div class="error" id="emailError">
Required: Please enter your email address
</div>
<div class="error" id="emailError2">
This doesn't look like a real email address, please check and reenter
</div>
<label for="FieldData2"><strong>Email:</strong>(will not be published)</label>
<input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
</div>
<div>
<div class="error" id="categoryError">
Please select a category from the drop-down menu
</div>
<label for="FieldData3"><strong>Category:</strong></label>
<select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select>
</div>
<div>
<div class="error" id="questionError">
Please type your question in the box below:
</div>
<label for="FieldData1"><strong>Your Question:</strong></label>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea>
</div>
<input type="submit" class="btn" value="Submit Question" name="Submit">
</form>
这篇关于内嵌的JavaScript表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!