验证用户为18

时间:2018-09-30 03:25:07

标签: c# validation asp.net-core-2.1

我使用Tahir Naushad ASP.NET Core 2.0 MVC Model Validation创建了以下内容:

从“注册”页面:

   public class FDRegisterModel : PageModel
{

    private readonly SignInManager<FDUser> _signInManager;
    private readonly UserManager<FDUser> _userManager;
    private readonly ILogger<FDRegisterModel> _logger;
    private readonly IEmailService _emailSender;

    public FDRegisterModel(
        UserManager<FDUser> userManager,
        SignInManager<FDUser> signInManager,
        ILogger<FDRegisterModel> logger,
        IEmailService emailSender
        )
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
        _emailSender = emailSender;
    }

    [BindProperty]
    public InputModel Input { get; set; }

    public string ReturnUrl { get; set; }



    public class InputModel
    {
        ...
        [Required]
        [DataType(DataType.Date)]
        [AgeCheck]
        [Display(Name = "Date of birth:")]
        public DateTime Birthday { get; set; }

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var FDuser = new FDUser { UserName = Input.UserName, Email = Input.Email };
            var result = await _userManager.CreateAsync(FDuser, Input.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation(Input.UserName + "was created.");

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(FDuser);
                var callbackUrl = Url.Page(
                    "/Profile/ConfirmEmail",
                    pageHandler: null,
                    values: new { FDUsername = FDuser.UserName, code = code },
                    protocol: Request.Scheme);

                await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                await _signInManager.SignInAsync(FDuser, isPersistent: false);
                return LocalRedirect(returnUrl);
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

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

来自FDUser模型:

public DateTime Birthday { get; set; }

从AgeCheck模型:

public class AgeCheck : ValidationAttribute
{
    //public DateTime Eighteen = DateTime.Now.Date.AddDays(-6570);
    public DateTime Birthday { get; set; }

    private string GetErrorMessage()
    {
        return $"Users of this website must be eighteen years of age.";
    }

    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {
        var model = validationContext.ObjectInstance as FDUser;

        if (model == null)
            throw new ArgumentException("No birthday given");

        if (model.Birthday > DateTime.Now.Date.AddDays(-6570))
            return new ValidationResult(GetErrorMessage(validationContext));

        return ValidationResult.Success;
    }

    private string GetErrorMessage(ValidationContext validationContext)
    {
        if (!string.IsNullOrEmpty(this.ErrorMessage))
            return this.ErrorMessage;

        return $"Users of this website must be eighteen years of age.";
    }
}

它返回null

Age check error

我也看过Microsofts article,我希望有这样一个更简单的东西:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    if (Birthday > Eighteen)
    {
        return new ValidationResult(GetErrorMessage());
    }

    return ValidationResult.Success;
}

但是我也无法正常工作。

1 个答案:

答案 0 :(得分:0)

正如Kirk所建议的那样,我使用了第二个更简单的选项,并使其能够与此代码一起使用。 (如果您好奇数学为什么看起来不正确,那么额外的日子就是leap年)

public sealed class AgeCheck : ValidationAttribute
    {
        public DateTime Birthday;
        public DateTime Eighteen = DateTime.Now.Date.AddDays(-6573);

        protected override ValidationResult IsValid(object Birthday, ValidationContext validationContext)
        {
            if (Eighteen <= Convert.ToDateTime(Birthday))
            {
                return new ValidationResult("You must be eighteen to use this website");
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }