嵌套對象的遠端 ViewModel 驗證不起作用
我有一個看起來像這樣的類使用者:
public class User { public int UserId { get; set; } [Required(ErrorMessage = "A username is required.")] [StringLength(20, ErrorMessage = "Your username must be 4-20 characters.", MinimumLength = 4)] [RegularExpression("^[a-zA-Z0-9]*$", ErrorMessage = "Your username can only consist of letters and numbers.")] [Remote("UsernameExists", "RemoteValidation", ErrorMessage = "Username is already taken")] public string Username { get; set; } [Required(ErrorMessage = "A password is required.")] [MinLength(4, ErrorMessage = "Your password must have at least 4 letters.")] public string Password { get; set; } [Required(ErrorMessage = "An email address is required.")] public string Email { get; set; } }對於註冊功能,我創建了一個 ViewModel,其中包含一個使用者對象和一個用於密碼確認的字元串:
public class RegistrationViewModel { public User User { get; set; } [DisplayName("Password confirmation")] [Required, Compare("User.Password", ErrorMessage = "The password do not match")] public string PasswordConfirmation { get; set; } }我遇到的第一個問題是我似乎無法驗證 Compare(“User.Password”) 的工作,因為它似乎沒有找到使用者的屬性。有沒有辦法根據 User.Password 屬性驗證 PasswordConfirmation 屬性?
第二個問題是使用者名欄位的遠端驗證。我在http://davidhayden.com/blog/dave/archive/2011/01/04/ASPNETMVC3RemoteValidationTutorial.aspx遵循了 David Hayden 的教程,但 UsernameExists 方法中的參數使用者名始終為空。我在這裡錯過了什麼嗎?
編輯:
對不起,但我實際上對密碼比較收到的錯誤還不夠清楚。填寫欄位時效果很好,如果密碼不匹配,我將收到錯誤消息。但是,在送出表單時,我在驗證摘要中收到以下錯誤:找不到名為 UserToRegister.Password 的屬性。
編輯2:
由於喬的文章,我已經解決了部分問題。遠端驗證器發回 URL/?UserToRegister.Username=temp 這顯然與我的控制器操作的使用者名參數不匹配。為了將我的操作參數映射到 UserToRegister.Username,需要以下內容:
public ActionResult UsernameExists([Bind(Prefix = "UserToRegister.Username")]string username)這現在可以正確地將參數傳遞給方法。但是,在密碼欄位上使用比較屬性時,我仍然會收到錯誤消息。
謝謝。
針對 User.Password 屬性驗證 PasswordConfigurmation 屬性的問題是由“jquery.validate.unobtrusive.js”文件中的錯誤引起的。
原來,jquery ’equalTo’ 函式是:
adapters.add("equalto", ["other"], function (options) { var prefix = getModelPrefix(options.element.name), other = options.params.other, fullOtherName = appendModelPrefix(other, prefix), element = $(options.form).find(":input[name=" + fullOtherName + "]")[0]; setValidationValues(options, "equalTo", element); });你只需要修改這一行:
element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];到:
element = $(options.form).find(":input[name='" + fullOtherName + "']")[0];請注意在“fullOtherName”選擇器周圍的單引號中添加的內容。進行此更改後,客戶端驗證將按預期工作。