我做了這驗證電子郵件是否已存在於我的數據庫這樣的自定義數據註解屬性屬性:自定義數據註釋驗證與客戶端驗證
[ValidateEmail(ErrorMessage = "Email exists")]
[Required(ErrorMessage = "Required")]
[RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Invalid Email")]
public string Email { get; set; }
這工作完全當頁面重新加載......但我現在想改變這種做法,我啓用客戶端驗證和消息顯示無需重新加載頁面本身...
我怎麼能修改此驗證屬性,使之與.NET MVC jQuery的unobstrusive驗證compliable?
基於@薩揚的鏈接,我已經實現了這樣的事情:
public class ValidateEmail : ValidationAttribute, IClientValidatable
{
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "emailvalidate";
yield return rule;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
using (var ctx = new myContext())
{
if (value != null)
{
var valueAsString = value.ToString().ToLower();
IEnumerable<string> email = ctx.Users.Where(x => x.Email != null).Select(x => x.Email);
if (email.Contains(valueAsString))
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
}
和客戶端:
$.validator.addMethod("emailvalidate", function (value, element) {
{
console.log("value: " + value + " " + element);
}});
$.validator.unobtrusive.adapters.add("emailvalidate", function (options) {
//adding rules for validator
options.rules["emailvalidate"] = true;
if (options.message) {
options.messages["emailvalidate"] = options.message;
}
});
但是,不管我在電子郵件字段現在插入電子郵件,如:
[email protected]
我收到電子郵件存在的錯誤?
任何人? =) – User987
如果要調用服務器方法,請使用'[Remote]'屬性。不要把數據庫調用了'ValidationAttribute' –