TyForHelpDude
TyForHelpDude

Reputation: 5002

.net mvc data annotation model state return always true

When I post an invalid serial, its set to ""(empty string) and I expect ModelState.isValid is false but it returns true.. here is my code.

        private string _tcno { get; set; }  

        [Required(ErrorMessage = "Enter serial")]
        [StringLength(11, MinimumLength = 11, ErrorMessage="Invalid Serial Number")]
        [Column(TypeName = "nchar")]
        public string TCNO
        {
            get { return _tcno ?? ""; }
            set { 
                 value = value ?? ""; 
                 _tcno = value.IsValidTC() ? value : ""; 
            }
        }

I trust min 11 length validation why ModelState.isValid is true here?

Upvotes: 1

Views: 365

Answers (2)

TyForHelpDude
TyForHelpDude

Reputation: 5002

Woking copy below is using my validation method and sets '-' if its invalid serial number, this way validatior error message is as I expected.

private string _tcno { get; set; }
        [Required(ErrorMessage = "Enter Serial")]
        [StringLength(11, MinimumLength = 11, ErrorMessage="Invalid Serial Number.")]
        [Column(TypeName = "nchar")]
        public string TCNO
        {
            get { return _tcno ?? ""; }
            set {
                value = value.IsValidTC() ? value : "-";
                _tcno = value;
            }
        }

Upvotes: 0

kblau
kblau

Reputation: 2107

Hopefully this will help. I did the following and I got a 'valid' for 12345678901 and I got 'invalid' for 1234

View:

@model Testy20161006.Controllers.AttributeViewModel
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>IndexValid10</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.TextBoxFor(r => r.TCNO);
            <input type="submit" value="submit" />
        }
    </div>
</body>
</html>

Controller/ViewModel:

public class AttributeViewModel
{
    private string _tcno { get; set; }

    [Required(ErrorMessage = "Enter serial")]
    [StringLength(11, MinimumLength = 11, ErrorMessage = "Invalid Serial Number")]
    [Column(TypeName = "nchar")]
    public string TCNO
    {
        get { return _tcno ?? ""; }
        set
        {
            value = value ?? "";
            //modified this line
            _tcno = value;
        }
    }
}

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult IndexValid10(AttributeViewModel attributeViewModel)
    {
        //set a breakpoint here
        if (ModelState.IsValid)
        {
            var isValid = true;
        }
        return View();
    }

Upvotes: 1

Related Questions