2013-05-06 5 views
0

JS 인증 코드에 문제가 있습니다. 양식을 제출하고 오류가 발생하면 양식을 더 이상 진행해서는 안됩니다. 그러나 코드는 멈추지 않고 다음 줄로 넘어가는데, 여전히 오류가 있지만 성공적인 메시지를 보여줍니다.자바 스크립트 유효성 검사가 exepected로 수행되지 않습니다.

그리고 명확하게 다음 return false ...

return false 다음 라인의 코드 캐리 비어있다 않습니다 필드가 예를 들어, 비록 있음을 서면으로 작성했습니다?

submit을 누르면 내 뜻을 알 수 있습니다.

JS :

(function(window, $) { 

    var Namespace = (function(Namespace) { 

     Namespace = { 

      // Main 
      run : function() { 
       this.validate.run('form'); 
      },    

      // Validation 
      validate : { 

       // error message span 
       messageBox : '<span class="message" />', 

       // add any field here 
       fields : { 
        nameField : $('#contact-name'), 
        emailField : $('#contact-email'), 
        phoneField : $('#contact-phone') 
       }, 

       // run validation 
       run : function(formName) { 

        $(formName).on('submit', $.proxy(this.validateField, this)); 
       }, 

       validateField : function() { 
        for (var field in this.fields) { 
         if (this.fields.hasOwnProperty(field)) { 
          this.checkField(this.fields[field]); 
         } 
        } 

        $('#general-message-section').text('Form successfully sent, thank you!'); 
        return false; 
       }, 

       checkField : function(field) { 

        var messageBox = $(this.messageBox); 

        field.closest('li').find('.message').remove(); 

        if (field.hasClass('required')) { 
         if (!field.val()) { 
          messageBox.text('This field is empty!'); 
          field.closest('li').append(messageBox); 
          return false; 
         } 
        } 

        if (this.fields.emailField.val()) { 
         this.fields.emailField.closest('li').find('.message').remove(); 

         if (!this.fields.emailField.val().match(this.regEx.email)) { 
          messageBox.text('Only email format accepted!'); 
          this.fields.emailField.closest('li').append(messageBox); 
          return false; 
         } 
        } 

        if (this.fields.phoneField.val()) { 
         this.fields.phoneField.closest('li').find('.message').remove(); 

         if (!this.fields.phoneField.val().match(this.regEx.numbers)) { 
          messageBox.text('Only numbers are accepted!'); 
          this.fields.phoneField.closest('li').append(messageBox); 
          return false; 
         } 
        } 
       }, 

       regEx : { 
        email : /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/, 
        numbers : /^[0-9]+$/ 
       } 
      } 
     }; 

     return Namespace; 

    }(Namespace || {})); 

    // make global 
    window.Namespace = Namespace; 

}(window, jQuery)); 

// run it... 
Namespace.run(); 

HTML :

<p id="general-message-section"></p> 
<form id="contact-form" method="post" action="#"> 
    <fieldset> 

     <ul> 
      <li> 
       <label for="contact-name">Contact name *:</label> 
       <input type="text" id="contact-name" tabindex="1" class="required" autofocus /> 
      </li> 
      <li> 
       <label for="contact-email">Contact email address *:</label> 
       <input type="text" id="contact-email" tabindex="2" class="required" /> 
      </li> 
      <li> 
       <label for="contact-phone">Contact phone number:</label> 
       <input type="text" id="contact-phone" tabindex="3" /> 
      </li> 
      <li> 
       <input type="submit" id="submit-btn" tabindex="4" value="Submit" /> 
      </li> 
     </ul> 
    </fieldset> 
</form> 

많은 감사

+1

질문 자체에 관련 코드를 게시하는 것이 더 쉽습니다 (다른 사용자의 경우). – techfoobar

+1

나중에 참고할 점으로, 귀하의 코드 사본을 귀하의 질문에 붙여 넣으십시오. – ericosg

+2

당신의 답신 거짓은 당신의 메시지 뒤에 있으므로 자연히 그들은 순서대로 실행됩니다. 다른 함수 내부로 복귀해도 상위 함수가 중단되지 않습니다. 내부 함수의 결과를 확인하고 false이면 반환해야합니다. – ericosg

답변

1

이, 그것은 유효한 루프 후 false 인 경우 확인하고 휴식 모든 필수 필드를 확인하고는 false를 반환하지만 실 거예요 루프를 위해 휴식 checkField() 경우 false로 valid을 설정합니다 :

 validateField : function() { 
      var valid = true; 
      for (var field in this.fields) { 
       if (this.fields.hasOwnProperty(field)) { 
        if(this.checkField(this.fields[field]) === false) valid = false; 
       } 
      } 
      if(!valid) return false; 

      $('#general-message-section').text('Form successfully sent, thank you!'); 
     } 

jsfiddle

2

나는 당신이 당신의 유효성 검사 논리에 체크를 누락 것 같아요. 코드 :

validateField : function() { 
    for (var field in this.fields) { 
     if (this.fields.hasOwnProperty(field)) { 
      this.checkField(this.fields[field]); 
     } 
    } 

    $('#general-message-section').text('Form successfully sent, thank you!'); 
    return false; 
}, 

checkField를 호출하지만, 그 결과를 (거짓 일 수있는) 확인하지 않습니다 않습니다. 난 당신과 같이있을 수 추측 : 그것은 (끝) 맞습니다 경우

validateField : function() { 
    for (var field in this.fields) { 
     if (this.fields.hasOwnProperty(field)) { 
      if(!this.checkField(this.fields[field])) { 
       alert("There are errors!"); 
       return false; 
      } 
     } 
    } 

    $('#general-message-section').text('Form successfully sent, thank you!'); 
    return false; 
}, 

그리고 checkField 코스 return true;의를, 그렇지 않으면 중 하나가 작동하지 않습니다.

+0

@Meta에 감사 드려요.하지만 한 필드 만 오류가 표시되고 있습니다. 동시에 각 필드가 비어 있기 때문에 각 필드에 동시에 오류 메시지가 표시되기를 원합니다. 어떻게해야합니까? – Shaoz

+0

'validateField' 함수에서'true'로 초기화 된 부울을 가질 수 있습니다.'checkField' 호출이 false 일 때마다'false'로 설정합니다. 루프가 부울을 확인한 후 필요한 메시지를 표시합니다 (오류 또는 성공). 제대로 작동하려면'checkField'가 필요합니다. 모든 것이 괜찮 으면'true'를 반환해야합니다. 희망이 도움이됩니다! – Meta

+0

checkField에서 true를 반환 할 필요는 없습니다. checkField가 fasle과 동일한 지 확인하는 대신 내 대답을 확인할 수 있습니다. – razzak

관련 문제