2012-05-23 3 views
0

Вот базовая электронная форму с math Captcha. Captcha работает, но валидатор формы - нет. Когда я говорю валидатор формы, я имею в виду требуемые поля «Имя» и «Электронная почта». Если я удалю код Captcha, средство проверки формы отлично работает. Я думаю, что код js для проверки формы и код js для Captcha каким-то образом конфликтуют друг с другом.Конфликт валидатора формы Javascript с математикой CAPTCHA

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>EiP - Contact Us</title> 

<script type="text/javascript"> 
// Form validator for the required Name and Email fields 
function MM_validateForm() { //v4.0 
    if (document.getElementById){ 
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; 
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]); 
     if (val) { nm=val.name; if ((val=val.value)!="") { 
     if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); 
      if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; 
     } else if (test!='R') { num = parseFloat(val); 
      if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; 
      if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); 
      min=test.substring(8,p); max=test.substring(p+1); 
      if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; 
     } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } 
    } if (errors) alert('The following error(s) occurred:\n'+errors); 
    document.MM_returnValue = (errors == ''); 
} } 
</script> 
</head> 
<body> 
    <p>Do you have a question or comment about EiP? We want to hear from you as your feedback is critical to our success.</p> 
    <p class="required">*Required info</p> 
    <form action="contactus.html" method="post" name="contactform" id="contactform" onsubmit="return checkform(this);MM_validateForm('name','','R','email','','RisEmail');return document.MM_returnValue"> 
    <p class="allforms">Full Name<span>*</span></p> 
    <input name="name" type="text" id="name"/>       
    <p class="allformsRt">Email Address<span>*</span></p> 
    <input type="text" name="email" id="email" /> 
    <p class="allforms">Company</p> 
    <input name="company" type="text" id="company" /> 
    <p class="allformsRt">Phone Number</p> 
    <input type="text" name="phone" id="phone" /> 
    <p class="allforms">How can we help?</p> 
    <textarea name="application" cols="35" rows="5" title="title" label="label" style="float:left">Type your questions, comments, feedback</textarea> 
    <label for="code" style="float:left; clear:both">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code --> 
    <input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field --> 
    <input type="text" name="txtInput" id="txtInput" size="30" style="float:left; clear:both" /> 
    <input name="Submit" type="submit" value="Contact Us" style="float:left; clear:both" /> 
     </form> 

<script type="text/javascript"> 
//Generates the captcha function  
    var a = Math.ceil(Math.random() * 9)+ ''; 
    var b = Math.ceil(Math.random() * 9)+ '';  
    var c = Math.ceil(Math.random() * 9)+ ''; 
    var d = Math.ceil(Math.random() * 9)+ ''; 
    var e = Math.ceil(Math.random() * 9)+ ''; 

    var code = a + b + c + d + e; 
    document.getElementById("txtCaptcha").value = code; 
    document.getElementById("txtCaptchaDiv").innerHTML = code; 
</script> 

<script type="text/javascript"> 
function checkform(theform){ 
    var why = ""; 

    if(theform.txtInput.value == ""){ 
     why += "- Security code should not be empty.\n"; 
    } 
    if(theform.txtInput.value != ""){ 
     if(ValidCaptcha(theform.txtInput.value) == false){ 
      why += "- Security code did not match.\n"; 
     } 
    } 
    if(why != ""){ 
     alert(why); 
     return false; 
    } 
} 

// Validate the Entered input aganist the generated security code function 
function ValidCaptcha(){ 
    var str1 = removeSpaces(document.getElementById('txtCaptcha').value); 
    var str2 = removeSpaces(document.getElementById('txtInput').value); 
    if (str1 == str2){ 
     return true;  
    }else{ 
     return false; 
    } 
} 

// Remove the spaces from the entered and generated code 
function removeSpaces(string){ 
    return string.split(' ').join(''); 
} 
</script> 
</body> 
</html> 
+0

WTF? Не могли бы вы переформатировать свой код JavaScript, чтобы мы могли «видеть» структуру, не получив массивной головной боли ... – Andreas

+0

Мне очень жаль ... я все еще изучаю javascript. как он должен быть реструктурирован? – halcyon9

+1

Префикс MM_ для проверки подлинности показал, что вы используете законсервированный скрипт Dreamweaver (MM - это наследие для MacroMedia). Сделайте себе одолжение и найдите более простой скрипт проверки. Вы узнаете больше об этом, и тот факт, что у вас есть конфликт, - отличная причина держаться подальше от законсервированных скриптов. – mmcglynn

ответ

1

Ваша onsubmit часть не может быть сделано таким образом. Если код безопасности верен, вы возвращаете undefined, что не является ложным, и поэтому форма отправляется перед вызовом функции MM_validateForm, которая проверяет требуемые поля.

Удалите onsubmit=... часть из разметки и добавьте следующий код на свой сайт

<script type="text\javascript"> 
    window.onload = function() { 
     var form = document.getElementsByTagName("form")[0]; // get the form 
     form.onsubmit = function() { 
      if (checkform(this) != false) { 
       MM_validateForm('name', '', 'R', 'email', '', 'RisEmail'); 
       return document.MM_returnValue; 
      } else { 
       return false; 
      } 
     }; 
    } 
</script> 

Demo

+0

OMG! Спасибо огромное! Я попробовал простой валидатор, как было предложено выше, но он все еще не работал. Это работает отлично. Еще раз спасибо! – halcyon9

+0

Добро пожаловать :) – Andreas