2014-02-13 211 views
2

我有一個小的提交表單http://wines.effectwave.com/我試圖用Jquery進行驗證。我想檢查是否有人用默認值提交表單(例如「全名」),那麼它應該提出錯誤。到目前爲止,我已經對空值和最小字符進行了驗證。但是,我如何檢查這個默認值的條件?這是我的JQuery代碼到目前爲止:Jquery輸入表單默認值驗證

// JavaScript Document 

$().ready(function() { 

    // validate signup form on keyup and submit 
    $("#regform").validate({ 
     rules: { 

      fname: { 
       required: true, 
       minlength: 3 
      }, 

      phone: { 
       required: true, 
       minlength: 8 
      }, 

      comments: { 
       required: true, 
       minlength: 5 
      }, 
      email: { 
       required: true, 
       email: true 
      }, 
     }, 

     messages: { 

      fname: { 
       required: "Please enter your full name", 
       minlength: "Your full name must consist of at least 3 characters" 
      }, 

      phone: { 
       required: "Please enter your phone number", 
       minlength: "Your phone number must consist of at least 8 characters" 
      }, 

      comments: { 
       required: "Please provide some comments", 
       minlength: "Your comments must be at least 5 characters long" 
      }, 
      email: "Please enter a valid email address", 
     } 
    }); 

}); 
+0

佔位符

更多信息,據我所知,'validate'不是一個jQuery功能。所以你可能使用了一個插件。哪一個? –

+1

他很明顯使用jquery-validate:http://jqueryvalidation.org/ – Barmar

+2

爲什麼使用默認值而不是佔位符? – Barmar

回答

0

您必須創建自定義驗證方法並將其添加到jQuery驗證器。

$(document).ready(function() { 
//add your custom method to validator 
    $.validator.addMethod("DefaultCheck", function (value, element) { 
     return value == "FullName" || "SomeOtherDefaultvalue"; // Default values to check against 
    }, 'Please add a valid fullname'); //Validation Message 

    $("#regform").validate({ 
     rules: { 

      fname: { 
       required: true, 
       minlength: 3, 
       DefaultCheck: true // your custom method 
      } 
     } 
    }); 

}); 
-1

您可以使用不等於。 J查詢文檔不清楚這...

jQuery.validator.addMethod("notEqual", function(value, element, param) { 
return this.optional(element) || value != $(param).val(); 
}, "The value can not be: " + value); 
    $("#regform").validate({ 
      rules: { 

       fname: { 
        required: true, 
        minlength: 3, 
        notEqual:'Full Name' 
       }, 

       phone: { 
        required: true, 
        minlength: 8 
       }, 

       comments: { 
        required: true, 
        minlength: 5 
       }, 
       email: { 
        required: true, 
        email: true 
       }, 
      } 
+0

我不知道'notEqual',你有沒有任何文檔鏈接? –

+0

我不抱歉,就像我在帖子中說的那樣,J查詢文檔在這個部分很差。如果答案有效,請投票支持:-) – lauksas

+0

**文檔沒有問題,因爲在[jQuery](https://api.jquery.com)中沒有'notEqual' **這樣的東西,或者[jQuery Validate插件](http://jqueryvalidation.org)。這個答案是純粹的幻想,應該刪除。 – Sparky

1

你可以考慮在HTML中使用佔位符而不是值?

反過來,這:

<input type="text" name="fname" id="fname" value="Full Name"... 

到:

<input type="text" name="fname" id="fname" placeholder="Full Name"... 

它看起來是一樣的,但實際的「價值」是空的,所以你應該能夠檢查,如果他們是在全部填滿。在http://www.w3schools.com/tags/att_input_placeholder.asp