Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually validate a model with attributes?

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?

like image 472
BrunoLM Avatar asked Jun 16 '13 23:06

BrunoLM


People also ask

What is attribute validation?

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.


1 Answers

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); 
like image 114
James Santiago Avatar answered Sep 21 '22 23:09

James Santiago