2016-10-31 33 views
0

我想使用歐芹的js自定義驗證器來檢查我的表單上唯一的電子郵件地址。然而,當我不管我回來的時候,它不會停止提交表單。獨特的用戶名和歐芹js

Ajax請求checkEmailExists取決於如果電子郵件存在

window.Parsley 
    .addValidator('uniqueUsername', { 
    requirementType: 'string', 
    validateString: function(value, requirement) { 
     $.ajax({ 
     url: "checkEmailExists", 
     data: {username: value}, 
     dataType: 'json', 
     method: 'POST', 
     data: { email: $("#email").val() }, 
     async: false, 
     success: function(data) { 
      return data; 
     } 
     }); 
    }, 
    messages: { 
     en: 'This email address already exists!' 
    } 
    }); 

<input type="text" id="email" name="email" placeholder="Email" data-parsley-uniqueUsername data-parsley-required="true" data-parsley-type="email"/> 

回答

1

你必須返回失敗或成功,與truefalse不會成功的承諾返回true或false。

最簡單的可能是使用remote驗證程序。

不相關,但對於像這樣的冪等請求,您應該使用GET而不是POST

0

正如馬克說你的諾言必須失敗成功,也是你的校驗器名不能有大寫字母或特殊字符,所以嘗試這樣的事:

// uniqueUsername validator 
window.Parsley.addValidator('uniqueusername', { 
    validateString: function (value, requirement) { 

     xhr = $.ajax({ 
      url: "users_list_ajax.php", 
      dataType: 'json', 
      method: 'GET', 
      data: { 
       action: 'checkUserExists', 
       username: value 
      } 
     }); 

     return xhr.then(function (data) { 
      console.log((data.isUnique == 0)); 

      if (data.isUnique == 0) { 
       return true; 
      } else { 
       return $.Deferred().reject(); 
      } 
     }); 
    }, 
    messages: { 
     en: 'Username already exists!', 
     ar: 'إسم المستخدم موجود مسبقا' 
    }, 
    priority: 32 
});