2014-02-26 24 views
0

http://jsfiddle.net/Nvt2h/如何使input.error適用於所有領域?

我正在使用此腳本將輸入字段的詳細信息發送到我的電子郵件。正如你所看到的那樣,如果輸入不正確,就會出現input.error,它將突出顯示紅色區域。但是,這隻適用於字段1和字段4.

如何在字段2和字段3上進行此項工作?

<form id="contact" name="contact" action="#" method="post"> 
<div class="form-group"> 
    <label for="msg">Field1: 

    </label> 
    <input name="msg" type="msg" class="form-control" id="msg"> 
</div> 
<div class="form-group"> 
    <label for="id">Field2:</label> 
    <input name="id" type="msg" class="form-control" id="msg"> 
</div> 
<div class="form-group"> 
    <label for="pb">Field3: 

    </label> 
    <input name="pb" type="msg" class="form-control" id="pb"> 
</div> 
<div class="form-group"> 
    <label for="email">Field4:</label> 
    <input name="email" type="email" class="form-control" id="email"> 
</div> 
<button id="send">Submit</button> 

+0

輸入1和2具有相同的id – Alex

+0

@Alex是啊試圖添加,看看是否會幫助,但它沒有。如果他們有不同的ID,它不會工作。 – user3187469

+2

你沒有對這些字段應用任何驗證。你想驗證什麼 –

回答

0

添加屬性MINLENGTH於這些輸入字段

<input name="msg" type="msg" class="form-control msg" id="msg" minlength="2"> 

然後

function validateEmail(email) { 
    var reg = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
    return reg.test(email); 
} 

$(document).ready(function() { 
    //$(".modalbox").fancybox(); 
    $("#contact").submit(function() { 
     return false; 
    }); 


    $("#send").on("click", function() { 
     $('#contact input.error').removeClass('error'); 

     var emailval = $("#email").val(); 
     var mailvalid = validateEmail(emailval); 
     if (mailvalid == false) { 
      $("#email").addClass("error"); 
     } 

     var minlen = $('#contact input[minlength]').filter(function(){ 
      return this.value.length < +$(this).attr('minlength') 
     }).addClass('error').length; 

     if (mailvalid == true && minlen == 0) { 
      // if both validate we attempt to send the e-mail 
      // first we hide the submit btn so the user doesnt click twice 
      $("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>"); 

      $.ajax({ 
       type: 'POST', 
       url: 'send.php', 
       data: $("#contact").serialize(), 
       dataType: 'jsonp', 
       success: function (data) { 
        if (data.result == true) { 
         $("#contact").fadeOut("fast", function() { 
          $(this).before("<p class='success'><strong>Thank you, your message has been sent. We will be in touch shortly.</strong></p>"); 
         }); 
        } else { /* if you want to handle mail send failed, put it here */ 
        } 
       }, 
       error: function (jqXHR, textStatus, errorThrown) { 
        // this is triggered if there's a problem getting the jsonp back from the server 
       } 
      }); 
     } 
    }); 
}); 

演示:Fiddle

+0

謝謝。您是否也知道如何將字段1替換爲