我不想让 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/