Validating the model outside of the controller in ASP.NET
Validating the model outside of the controller in ASP.NET:
Model validation with Data Annotations, the MVC framework will usually automated to handle the performance of actual validation and results to the end-user.
To validate the model outside of controller,we can create a sample of console application into the same application or in other application also.
Here,We are using class named User model:


using System.ComponentModel.DataAnnotations;
namespace ValidateExample
{
    public class User
    {
        [Required]
        [StringLength(20)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(25, MinimumLength = 3)]
        public string LastName { get; set; }

        [Required]
        [EmailAddress]
        public string EmailAddress { get; set; }
    }
}



I have created, within the same Solution, a Console App project.Here's our Console App:


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

namespace ValidateExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting validation:");

            User user = new User();
            user.FirstName = null;
            user.LastName = "aaa";
            user.Emailaddress = "eg@exam@example";

            var context = new ValidationContext(user, null, null);
            var results = new List&lt;ValidationResult&gt;();

            var isValid = Validator.TryValidateObject(user, context, results, true);

            if (!isValid)
            {
                Console.WriteLine("User is not valid! Errors are:");
                foreach (var validationResult in results)
                {
                    Console.WriteLine(validationResult.ErrorMessage);
                }
            }
            Console.WriteLine("Validation Complete...");
            Console.ReadKey();
        }
    }
}



We simply created a model named User and made some data-annotations in it.Then,In console class We putted some invalid values to test the application.
Here,We called the Validator.TryValidateObject() this function which validate the model according to the data-annotations.
Run the apllication :
The Console Output :-


Starting validation:
User is not valid! Errors are:
The FirstName field is required.    //(as We assigned null to FirstName field)
The EmailAddress field is not a valid email address.