2013-07-18 59 views
-2

以下表單使用JavaScript進行驗證,但不起作用。它仍然採取行動,而不是顯示錯誤。我無法弄清楚代碼有什麼問題。看起來很好。任何人都可以告訴我我的錯誤?使用java腳本進行表單驗證

<script type='text/javascript'> 

function formValidator(){ 

    var name = document.getElementById('name'); 
    var alpha = /^[a-zA-Z]+$/; 

    if(!alpha.test.(name.value)){ 
     alert('Please provide a valid name'); 
     name.focus; 
     return false; 

    } 

    var email = document.getElementById('email'); 
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 

    if (!filter.test(email.value)) { 
    alert('Please provide a valid email address'); 
    email.focus; 
    return false; 
} 
} 
</script> 

<div id="contact_form"> 
        <p>Stay Connected.</p> 
          </div> 
    <form name="contact" method="post" action="sendmail.php" onsubmit='return formValidator();'> 
    <fieldset> 
     <label for="name" id="name_label">Your name *</label> 
     <input type="text" name="name" id="name" size="50" value="" class="text-input" required /> 


     <label for="email" id="email_label">Your email address *</label> 
    <input type="text" name="email" id="email" /> 



     <br /> 
     <input type="submit" name="submit" class="button btn btn-primary btn-info" id="submit_btn" value="Send" onclick='Javascript:formValidator();'/> 
    </fieldset> 
    </form> 

I dont want to use only html5 validation. 
+0

定義「不工作」。 – 2013-07-18 12:20:06

+0

'name.focus;' - >'name.focus();''和'email.focus' - >'email.focus();' – dbanet

+0

這不是問題無論如何 – dbanet

回答

0

這是在控制檯中的錯誤

SyntaxError: missing name after . operator 
[Break On This Error] 

if(!alpha.test.(name.value)){ 

所以使用

if (!filter.test(name.value)) instead of if(!alpha.test.(name.value)){ 

刪除.

+0

thanks.it working.silly我的錯誤。 – 8bitrebellion

0

我猜if語句永遠不是真的,所以false永遠不會返回。

0

更換if (!filter.test.(name.value)) {

if (!filter.test(name.value)) { 
+0

thanks..anyway。 – 8bitrebellion