0

我有我的页面不显眼的客户端验证设置。错误消息从我们的数据库返回。对于需要添加参数的验证消息之一,我可以使用特定值对其进行格式化。这工作良好的服务器端,但我显然没有获得一些这些值时GetClientValidationRules方法是第一次安装。正因为如此,它看起来像我将不得不在我的客户端代码中建立错误消息,但我不知道如何执行此操作,因为您只需在jQuery.validator.addMethod中返回true或false。MVC3和自定义客户端验证消息

所以我基本上需要能够做的是在GetClientValidationRules方法中将ErrorMessage设置为string.Empty,然后在我的clinet端代码中进行验证,以便能够返回任何我想要的消息。

下面是客户端代码在MVC 3

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var rule = new ModelClientValidationRule 
         { 
          ValidationType = "maximumdatecoverrequired", 
          ErrorMessage = string.Empty, 
         }; 

     rule.ValidationParameters.Add("maxdate", DateTime.Now.AddDays(Settings.Default.MaximumDateCoverRequiredDaysInFuture).ToString("yyyy/MM/dd")); 

     return new[] { rule }; 
    } 

这里是我的客户端代码来验证这个特殊的财产被接线。

jQuery.validator.addMethod("maximumdatecoverrequired", function (value, element, params) { 
     var maxDate = new Date(params["maxdate"]); 
     var day = maxDate.getDate(); 
     var month = maxDate.getMonth() + 1; 
     var year = maxDate.getFullYear(); 

     var dateCoverRequired = new Date(value).toString('yyyy/MM/dd'); 
     maxDate = maxDate.toString('yyyy/MM/dd'); 

     if (value > maxDate) { 
      $("input#DateCoverRequired_Day").val(day); 
      $("select#DateCoverRequired_Month").val(month); 
      $("input#DateCoverRequired_Year").val(year); 
      return false; 
     } 

     return true; 
    }); 

如何在客户端代码中返回自定义消息?

+1

你想验证什么?缺少太多的细节 – gdoron 2011-12-15 12:27:38

回答

1

让我给你一个如何做到这一点的例子。我选择的例子是注册一个新用户并检查他们的名字。

我们要做的就是让用户选择一个用户名,如果它已经存在于数据库中,我们不会让他们拥有它并提出建议。

要做到这一点,我们将使用远程验证,它指向我们的控制器中的ActionMethod。

注册模式

public class RegisterModel 
    { 
     //This is the one I'm giving you the code for... 
     [Required] 
     [RegularExpression(@"(\S)+", ErrorMessage = "Username cannot contain spaces.")] 
     [Remote("CheckUserName", HttpMethod="POST")] 
     [Display(Name = "Username")] 
     public string UserName { get; set; } 

     // You can do this one yourself :-) 
     [Required] 
     [Remote("CheckEmailAddress", ErrorMessage="{0} already has an account, please enter a different email address.", HttpMethod="POST")] 
     [DataAnnotationsExtensions.Email(ErrorMessage="{0} is not a valid email address.")] 
     [Display(Name = "Email address")] 
     public string Email { get; set; } 

     [Required] 
     [ValidatePasswordLength] 
     [DataType(DataType.Password)] 
     [Display(Name = "Password")] 
     public string Password { get; set; } 

     [DataType(DataType.Password)] 
     [Display(Name = "Confirm password")] 
     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
     public string ConfirmPassword { get; set; } 
    } 

ActionMethod(通过模型引用的远程方法)

[HttpPost] 
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)] 
public JsonResult CheckUserName(string userName, Guid? userId = null) 
{ 
    if (userName != null || userName.Length > 2) 
    { 
     var users = Membership.FindUsersByName(userName); 
     if (users.Count == 0) 
     { 
       return Json(true); 
     } 
     else 
     { 
      if ((users[userName].ProviderUserKey as Guid?) == userId) 
      { 
       return Json(true); 
      } 
      else 
      { 
       string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available.", userName); 
       // Maybe this is a bit feeble, but it will loop around (inefficiently) and suggest a new username with a number on the end. EG Tom is not available. Try Tom37 
       for (int i = 1; i < 100; i++) 
       { 
        string altCandidate = userName + i.ToString(); 
        if (Membership.FindUsersByName(altCandidate).Count == 0) 
        { 
         suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available. Try {1}.", userName, altCandidate); 
         break; 
        } 
       } 
       // This is the important bit. I am returning a suggested UserName 
       return Json(suggestedUID, JsonRequestBehavior.AllowGet); 
      } 
     } 
    } 
    else 
    { 
     return Json(true); 
    } 
} 

我觉得这很酷,因为正则表达式确保没有空格,然后(如果没关系)将它提交给检查数据库的远程方法。