1

I want to not let people under age 18 to be able to be registered in the database. I have zero clue in how to do so. I already have the controller up. Here it is.

[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);
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
Longshadow
  • 109
  • 1
  • 1
  • 8

1 Answers1

6

If your users need to give their birthdate: Add a custom validation attribute like this in your model

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.");
    }
}

If Users have to give their age you can just add a range attribute to your model:

[Range(18, int.MaxValue)]
counterflux
  • 363
  • 3
  • 12