使用MVC5进行流畅验证

时间:2015-11-13 16:21:13

标签: c# fluentvalidation

我确实在C#和MVC5领域仍然非常环保,但每天都在学习,所以我非常感谢你对我缺乏知识的耐心。

我已经阅读了我能找到的所有内容,但仍然无法使用以下内容。说实话,我试图让清洁.Trial(密码)工作,但意识到这可能是我的头脑。这将是首选,但至少让这个丑陋的版本工作将是太棒了。 "试用"方法不会从我能告诉的方法调用,但是当我尝试使用断点调试它时,无法检查,因为我收到错误。

我的AccountViewModels.cs

中有以下内容
[Validator(typeof(RegisterViewModelValidator))]
public class RegisterViewModel {
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Display(Name = "Email")]
    public string Email { get; set; }

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

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    public string ConfirmPassword { get; set; }


}




public class RegisterViewModelValidator : AbstractValidator<RegisterViewModel> {
    public RegisterViewModelValidator() {

        RuleFor(x => x.UserName)
            .NotEmpty()
                .WithMessage("Username is required");

        RuleFor(x => x.Email)
            .NotNull()
                .WithMessage("E-mail is required")
            .EmailAddress()
                .WithMessage("E-mail is invalid");

        RuleFor(x => x.Password)
           .Must(password => Trial(password))
                .WithMessage("Password must triggered");

        RuleFor(x => x.ConfirmPassword)
            .Equal(x => x.Password)
                .WithMessage("Confimation odes not match");

    }

    private bool Trial(string value) {
        if (string.IsNullOrEmpty(value)) {
            return false;
        } else {
            return true;
        }
    }
}

以及我的Global.asax中的以下内容

 FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure();

这是我认为的

<div id="regesterFormContainer" class="col-md-4">


            @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id = "regesterForm", autocomplete = "off" })) {

                @Html.AntiForgeryToken()


                @Html.ValidationMessageFor(m => m.UserName, string.Empty, new { @class = "error-class" })
                @Html.TextBoxFor(m => m.UserName, new { id = "regesterUserNam", placeholder = "Username", @class = "registerFormInputs", title = "4-20 characters with letters, numbers, - and _" })


                @Html.ValidationMessageFor(m => m.Email, string.Empty, new { @class = "error-class" })
                @Html.TextBoxFor(m => m.Email, new { id = "regesterEhMell", placeholder = "E-Mail Address", @class = "registerFormInputs", title = "Must be a valid e-mail address." })


                @Html.ValidationMessageFor(m => m.Password, string.Empty, new { @class = "error-class" })
                @Html.PasswordFor(m => m.Password, new { id = "regesterPess", placeholder = "Password", @class = "registerFormInputs", title = "5-20 characters. An Uppercase letter, lowercase letter and a number are required." })

                @Html.ValidationMessageFor(m => m.ConfirmPassword, string.Empty, new { @class = "error-class" })
                @Html.PasswordFor(m => m.ConfirmPassword, new { id = "regesterConPess", placeholder = "Confirm Password", @class = "registerFormInputs", title = "Must match password above." })


                <div class="registerSubmitFrame">
                    <input type="submit" class="registerSubmit" value="Register">
                </div>
                <p><a id="showExtReg">Show external registration options</a></p>


            }



        </div>

适用的控制器块

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model) {
            if (ModelState.IsValid) {
                var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);


                var validator = new RegisterViewModelValidator();
                validator.Validate(model);  // viewmodel should be passed into the controller method on POST via model binding.



                if (result.Succeeded) {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

感谢您的时间和耐心

2 个答案:

答案 0 :(得分:0)

尝试:

RuleFor(x => x.Password)
    .NotEmpty()
         .WithMessage("Password in required")
    .Length(6, 100)
        .WithMessage("Password not long enough")
    .Must(Trial)
        .WithMessage("Password must triggered");

private bool Trial(RegisterViewModel viewModel, string value) {
    if (string.IsNullOrEmpty(value)) {
        return false;
    } else {
        return true;
    }
}

答案 1 :(得分:0)

在处理POST的控制器中,您可能会遇到绑定视图模型的问题。向我们展示您的控制器代码。

您可以将其放入控制器中进行验证:

var validator = new RegisterViewModelValidator();
validator.Validate(viewModel);  // viewmodel should be passed into the controller method on POST via model binding.

编辑:澄清,

The following validators are supported on the client:

NotNull/NotEmpty
Matches (regex)
InclusiveBetween (range)
CreditCard
Email
EqualTo (cross-property equality comparison)
Length

在OP的情况下,他应该使用&#34; NotEmpty&#34;这将取代这个&#34;必须&#34;逻辑:

   private bool Trial(string value) {
        if (string.IsNullOrEmpty(value)) {
            return false;
        } else {
            return true;
        }
    }

并且它将在jquery不显眼的客户端和服务器MVC模型验证上运行。