93

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?

5 Answers 5

137

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);
5
  • 8
    A doubt: why don't directly use the System.Web.Mvc.Controller.TryValidateModel(u) method?
    – Gianpiero
    Sep 5, 2017 at 10:24
  • 10
    @GianpieroCaretti because that gives unneeded references? This is most likely used in console applications or libraries most of the time. There is little to no need for this in normal situations when it comes down to a web application. Oct 23, 2019 at 10:12
  • 1
    @Viezevingertjes: I do agree.
    – Gianpiero
    Oct 23, 2019 at 10:31
  • Don't know what 'gives unneeded references' mean in This using context. Can someone explain please? Is [TryValidateModel] right there in controller and we create instance of object in that controller too?
    – dellos
    Feb 25, 2023 at 11:13
  • 1
    If we are validating within a controller, then Yes, we can use System.Web.Mvc.Controller.TryValidateModel(u). If we are not validating within a controller, adding a referece to System.Web.Mvc.Controller.TryValidateModel() would be an unneded reference since we don't use a controller.
    – kkuilla
    Jan 22 at 10:00
68

I made an entry in the Stack Overflow Documentation explaining how to do this:

Validation Context

Any validation needs a context to give some information about what is being validated. This can include various information such as the object to be validated, some properties, the name to display in the error message, etc.

ValidationContext vc = new ValidationContext(objectToValidate); // The simplest form of validation context. It contains only a reference to the object being validated.

Once the context is created, there are multiple ways of doing validation.

Validate an Object and All of its Properties

ICollection<ValidationResult> results = new List<ValidationResult>(); // Will contain the results of the validation
bool isValid = Validator.TryValidateObject(objectToValidate, vc, results, true); // Validates the object and its properties using the previously created context.
// The variable isValid will be true if everything is valid
// The results variable contains the results of the validation

Validate a Property of an Object

ICollection<ValidationResult> results = new List<ValidationResult>(); // Will contain the results of the validation
bool isValid = Validator.TryValidatePropery(objectToValidate.PropertyToValidate, vc, results, true); // Validates the property using the previously created context.
// The variable isValid will be true if everything is valid
// The results variable contains the results of the validation

And More

To learn more about manual validation see:

2
  • 3
    Remember to specify MemberName on the validation context when validating a property, e.g. vc.MemberName = nameof(objectToValidate.PropertyToValidate); Jan 10, 2020 at 11:31
  • TryValidatePropery seems like that is misspelled here and it only takes 3 parameters Ref: learn.microsoft.com/en-us/dotnet/api/… Jan 22 at 19:42
11

Since the question is asking specifically about ASP.NET MVC, you can use the TryValidateObject inside your Controller action.

Your desired method overload is TryValidateModel(Object)

Validates the specified model instance.

Returns true if the model validation is successful; otherwise false.

Your modified source code

[HttpPost]
public ActionResult NewUser(UserViewModel userVM)
{
    User u = new User();
    u.Name = null;

    if (this.TryValidateObject(u))
    {
        TempData["NewUserCreated"] = "New user created sucessfully";
        return RedirectToAction("Index");
    }

    return View();
}
1
  • 2
    Good, but what is the reason if TryValidateObject fails? I want to get more details about validation? Aug 23, 2020 at 14:46
10

I wrote a wrapper to make this a bit less clunky to work with.

Usage:

var response = SimpleValidator.Validate(model);

var isValid = response.IsValid;
var messages = response.Results; 

Or if you only care about checking validity, it's even tighter:

var isValid = SimpleValidator.IsModelValid(model);

Complete source:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Ether.Validation
{
    public static class SimpleValidator
    {
        /// <summary>
        /// Validate the model and return a response, which includes any validation messages and an IsValid bit.
        /// </summary>
        public static ValidationResponse Validate(object model)
        {
            var results = new List<ValidationResult>();
            var context = new ValidationContext(model);

            var isValid = Validator.TryValidateObject(model, context, results, true);
         
            return new ValidationResponse()
            {
                IsValid = isValid,
                Results = results
            };
        }

        /// <summary>
        /// Validate the model and return a bit indicating whether the model is valid or not.
        /// </summary>
        public static bool IsModelValid(object model)
        {
            var response = Validate(model);

            return response.IsValid;
        }
    }

    public class ValidationResponse
    {
        public List<ValidationResult> Results { get; set; }
        public bool IsValid { get; set; }

        public ValidationResponse()
        {
            Results = new List<ValidationResult>();
            IsValid = false;
        }
    }
}

Or at this gist: https://gist.github.com/kinetiq/faed1e3b2da4cca922896d1f7cdcc79b

0

There is another approach to validation, which is more easy reusable - FluentValidation

This library allows to play with inheritance, different rule sets for one model and has many other cool features. Read about advantages here.

With this library definition of validation rules is separated from model and code will look next way:

public class UserValidator:AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(x => x.Name).NotEmpty();
    }
}

Usage will look next way:

var validator = new UserValidator();
var validationResult = await validator.ValidateAsync(model);    
1
  • 1
    How is this more reusable? What if I had an AdminUser class with an AdminName property that should be non-empty - surely I'd have to create an AdminUserValidator, give it a constructor, and create the rule (i.e. no re-use, really). With the attribute approach, all I have to do is use the RequiredAttribute and stick it on any property I want (excellent re-use). (I'm not sure if NonEmpty here means "required and non-empty" or just "if it's present, it should not be empty". If the latter, an equivalent custom attribute can be created pretty effortlessly).
    – devklick
    Nov 13, 2022 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.