I have a class called User
and a property Name
public class User { [Required] public string Name { get; set; } }
And I want to validate it, and if there are any errors add to the controller's ModelState
or instantiate another modelstate...
[HttpPost] public ActionResult NewUser(UserViewModel userVM) { User u = new User(); u.Name = null; /* something */ // assume userVM is valid // I want the following to be false because `user.Name` is null if (ModelState.IsValid) { TempData["NewUserCreated"] = "New user created sucessfully"; return RedirectToAction("Index"); } return View(); }
The attributes works for UserViewModel
, but I want to know how to validate a class without posting it to an action.
How can I accomplish that?
Attribute Validation is an advanced VLDB property that is hidden by default. For information on how to display this property, see Viewing and Changing Advanced VLDB Properties.
You can use Validator to accomplish this.
var context = new ValidationContext(u, serviceProvider: null, items: null); var validationResults = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(u, context, validationResults, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With