MVC3和自定义客户端验证消息

时间:2011-12-15 12:25:28

标签: javascript asp.net-mvc-3 unobtrusive-javascript client-side-validation

我的页面有不显眼的客户端验证设置。从我们的数据库返回错误消息。对于其中一个验证消息,我需要添加参数,以便我可以使用特定值对其进行格式化。这可以很好地服务器端,但是当我第一次设置GetClientValidationRules方法时,我显然无法访问其中的一些值。因此,看起来我将不得不在客户端代码中构建错误消息,但我不知道如何执行此操作,因为您只需在jQuery.validator.addMethod中返回true或false。 / p>

所以我基本上需要做的是在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 个答案:

答案 0 :(得分:1)

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

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

为此,我们将使用指向控制器中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);
    }
}

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