2015-11-17 60 views
0
$(document).ready(function(){ 
    var form = $("#contact_form"); 
    var FName = $("#fname"); //Creates Variables from forms 
    var FNameInfo = $("#fnameInfo"); 
    var Tele = $("#tele"); 
    var TeleInfo = $("#teleInfo"); 
    var Address = $("#address"); 
    var AddressInfo = $("#addInfo"); 
    var Email = $("#email"); 
    var EmailInfo = $("#EmailInfo"); 
    var regexp = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_.-][email protected][a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9.]+.[a-z]{2,4}$/; //ragex code 

    FName.blur(validateFName); //blur is a method which attaches a functiom to run when an event occurs 
    Email.blur(validateEmail); 
    Tele.blur(validateTele); 
    Address.blur(validateAddress); 

    form.submit(function(){ 
     jQuery.validator.addMethod("noSpace", function(value, element) { //Code used for blank space Validation 
      return value.indexOf(" ") < 0 && value != ""; 
     }, "No space please and don't leave it empty"); 

     $("contact_form").validate({ 
      rules: { 
       name: { 
        noSpace: true 
       } 
      } 
     }); 

     if (validateFName() & validateTele() & validateEmail() & validateAddress()) { //If it passes all of these then return true 
      return true;  
     } else { 
      return false;   
     } 
    }); 

    function validateFName() { //Creates function for Name Validation+ 
     if (FName.val().length < 5) {  //If name is length is less than 5 
      FName.addClass("error"); //Display error 
      FNameInfo.text("Please Enter Correct Name"); //Changes span name 
      FNameInfo.addClass("error"); //Same error 
      FNameInfo.removeClass("Valid");     
      return false; 
     } 
     else { 
      FName.removeClass("error"); //remove error class 
      FNameInfo.addClass("Valid") 
      FNameInfo.text("Thanks Buddy"); //When user enters correct code this text will appear 
      FNameInfo.removeClass("error"); 
      return true; 
     } 
    } 
<div> 
    <label for="name">Full Name</label> 
    <input id="fname" name="fname" type="text" /> 
    <span id="fnameInfo">Whats your full name?</span> 
</div> 

我如何驗證爲全名工作時,用戶輸入空格?我有上面的代碼,但它似乎沒有做任何事情。我需要更改功能參數嗎?驗證jQuery的形式如何不讓空格全名

+0

你可以嘗試'回報(value.indexOf(」 「「)<0 &&值=!」)真:FALSE' – Rajesh

+0

包括真:?假的? –

回答

3

"contact_form"需要一個#爲id或.爲類。

name全名是fname

這樣: -

$("#contact_form").validate({ 
    rules: { 
     fname: { 
     noSpace: true 
     } 
    } 
}); 

應該工作。

FIDDLE

+0

感謝它以某種方式工作,但這只是當我按空間大約4倍的東西,它的行爲就像一個有效的輸入。 –

+0

其實不用擔心它工作謝謝! –

+0

非常有幫助的代碼 – chitra