c# - 未满18岁如何不注册

标签 c# asp.net asp.net-mvc

我不想让 18 岁以下的人能够在数据库中注册。我对如何这样做一无所知。我已经有 Controller 了。 在这里。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "nome,cpf,data_nasc")] clientes clientes)
{
    try
    {
        if (ModelState.IsValid)
        {
            db.Cliente.Add(clientes);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DataException /* dex */ )
    {
        ModelState.AddModelError("", "Não foi possível salvar as mudanças. Tente de novo e se o problema persistir entre em contato com o administrador de sistema.");
    }

    return View(clientes);
}

最佳答案

如果您的用户需要提供他们的生日: 在您的模型中添加这样的自定义验证属性

public class Over18Attribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string message = String.Format("The {0} field is invalid.", validationContext.DisplayName ?? validationContext.MemberName);

        if (value == null)
            return new ValidationResult(message);

        DateTime date;
        try { date = Convert.ToDateTime(value); }
        catch (InvalidCastException e) { return new ValidationResult(message); }

        if (DateTime.Today.AddYears(-18) >= date)
            return ValidationResult.Success;
        else
            return new ValidationResult("You must be 18 years or older.");
    }
}

如果用户必须提供他们的年龄,您可以向您的模型添加一个范围属性:

[Range(18, int.MaxValue)]

关于c# - 未满18岁如何不注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37477381/

相关文章:

C#:传递泛型数组

c# - 使表格在函数C#中可用

c# - 来自 wcf 服务的 Httpwebrequest

c# - 带有泛型的 NUnit 测试用例

asp.net - 获取项目的深度

c# - 从 Asp.Net MVC 中的 Html 内容生成 JPEG

c# - 插入登录用户的 UserID

C#/ASP.NET Selenium WebDriver - 重复使用 Cookie

c# - 将应用程序 Web 部署到单独的 Web 服务器后出现 SQL Server 错误

asp.net-mvc - 在 ASP.NET MVC DisplayFor Html Helper 中为空值显示 "NULL"