Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc duplicate user validation error

How can i can create a validation where i can only create 1 user with that name

my code

is this

  [HttpPost]
        public ActionResult Create(Klant klant)
        {
            ModelState.AddModelError("Firma", "Firma already exists");  

            if (ModelState.IsValid)
            {

                db.Klanten.Add(klant);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(klant);
        }

now can i create 0 users because i get always the error firma already exists with my addmodelerror

like image 652
Feren Avatar asked Mar 18 '23 22:03

Feren


1 Answers

First, check if your modelstate is valid. If it isn't, let the user know the had some invalid fields.

If it is valid, check if that username already exists, and if it does, return the model with your added model error:

public ActionResult Create(Klant klant)
{
    if (ModelState.IsValid)
    {
        if(db.Klanten.Any(k => k.Username == klant.Username)
           ModelState.AddModelError("Firma", "Firma already exists");
        else
        {
           db.Klanten.Add(klant);
           db.SaveChanges();
           return RedirectToAction("Index");
        }
    }

    return View(klant);
}

This approach is more user-friendly, as the last error they can have is a username already taken, and they'll only have to change that.

like image 191
Jonesopolis Avatar answered Mar 24 '23 10:03

Jonesopolis