2012-09-26 44 views
0

我正在使用jQuery Mobile最新版本和jQuery。在jQueryMobile中驗證字段

我需要驗證一個字段,它將接受用戶的輸入。

如果輸入不是數字,我希望有一個錯誤驗證消息接近該字段。

我想知道如何使它在jQuery Mobile中。

另外我想知道是否有可能強制用戶只添加一個字段的數值。

+0

是的,它是可能的,但首先告訴我你已經嘗試了什麼? – pkachhia

+0

如果你能爲我提供一個代碼示例,那我真的無法做到。讓我知道謝謝! – GibboK

回答

0

您可以使用http://docs.jquery.com/Plugins/Validation

如果你需要自定義驗證看一看addMethod(name, method, message)從這個插件

0

您可以使用jQuery Mobile的相同jquery.validate.js插件。其他方面,您可以添加一個類formField到需要驗證和提交的所有表單字段,獲取包含字段的元素並執行自定義驗證。如果您使用的是哈希的每一頁,我會寫一些東西,如:

<form class='myFormElem display-none'> 
    <div class="errorField" 
    <input type="text" data-regexp="^\+?[0-9]{10,15}$" class="formField"> 
    <input type="submit" class="submitForm"> 
</form 

的示例代碼段:

$(location.hash + ' .submitForm').off('click'); 
$(location.hash + ' .submitForm').on('click', function (e) { 
    $(location.hash + ' .formField').each(function() { 
     var elem = $(this), p, regexp; 
     try { 
      //validate fields 
      p = elem.data('regexp'); 
      if (p !== "" && p !== null && typeof p !== "undefined") { 
       regexp = new RegExp(p, ["g"]); 
       if (!val.match(regexp)) { 
        throw "Error..(your error message here)"; 
       } 
      } 
     } catch (ex) { 
      $(errField).removeClass('display-none').addClass('display-block'); 
      $(errField).html(ex); 
     } 
    } 
});