Search code examples
asp.net-mvcmodel-view-controllerviewbag

Validate and check for conditions and constrain for text box


I have a textbox called pass in my Create view

<div class="form-group">
       @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
       <div class="col-md-10">
            @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
</div>

In my AccountController, I tried to validate the password between 8 to 250 letters, the code doesnt seem to work properly as when I tried to run the website, it return error: 'Cannot perform runtime binding on a null reference'

            if (ModelState.IsValid)
            {
                db.Accounts.Add(account);
                if(ViewBag.Password.Length > 8 && ViewBag.Password != null)
                {
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else return RedirectToAction("Create");

Solution

  • Generally viewbag is used to send data from controller to view. and you already have model property so why you need to check with the viewbag?.

    For min and max length you can use data annotation and add attribute before the model property. it will be check at the ModelState.IsValid. you don't need to do extra code for that.

    eg.

    [MinLength(8,ErrorMessage = "Min length length should be 8"),MaxLength(250,ErrorMessage ="Max length should be 250")]
    public string Password { get; set; }
    

    you can also set regular expression for complex password as per you requirements.