Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
1.5k views
in .Net Framework by 66 69 85
edited by

I want to check for specific field is valid in my .NET Core MVC Project. I know there is the ModelState.IsValid method which check the entire Model, but i need to check only one property in the model.

below is my Model:

public class MyModel
{
	[Required(AllowEmptyStrings = false)]
	[StringLength(10)]
	[RegularExpression(@"^[0-9]*$", ErrorMessage = "Invalid ID")]
	[Display(Name = "IdentityNo")]

	[Required(AllowEmptyStrings = false)]
	[StringLength(256)]
	[RegularExpression(@"^[A-Za-z0-9\s!@#$%^&*()_+=-`~\\\]\[{}|';:/.,?]*$", ErrorMessage ="Invalid Email or username")]
	public string UserNameOrEmailAddress { get; set; }

	[Required(AllowEmptyStrings = false)]
	[StringLength(50)]
	[DataType(DataType.Password)]
	public string Password { get; set; }

}

 

If i use ModelState.IsValid will check all the model, and i want to check only ID property. below is how i check the validation in the Controller:

if (ModelState.IsValid)
{
    // code
}

it's will return false, because i only entry ID, username and password leve it empty.

How to check specific property in my Model?


1 Answer

1 like 0 dislike
by 66 69 85
 
Best answer

How to check specific field in .NET MVC

You can check one field in your model, like the example we will check only the ID property using ModelState["FieldName"] Instead of ModelState.IsValid

Like this:

 if(ModelState["ID"].Errors.Count > 0)
{
    foreach(var error in ModelState["ID"].Errors)
    {
        ModelState.AddModelError("", error.ErrorMessage);
        return View();
    }
}
// code
If you don’t ask, the answer is always NO!
...