Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6078307
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T10:49:06+00:00 2026-05-23T10:49:06+00:00

I have separate model and viewmodel classes. Where viewmodel classes only do UI level

  • 0

I have separate model and viewmodel classes. Where viewmodel classes only do UI level validation (refer: Validation: Model or ViewModel).

I can verify on post action in a controller that model (vewmodel) is valid.

The ask:
How do I validate the model (the main entity with data annotations).

I am not developing the viewmodel using model object. Just duplicating the properties and adding all properties possibly required in that particular view.

//Model Class
public class User
{
    [Required]
    public string Email {get; set;}

    [Required]
    public DateTime Created {get; set;}
}

//ViewModel Class
public class UserViewModel
{
    [Required]
    public string Email {get; set;}

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

//Post action
public ActionResult(UserViewModel uvm)
{
    if( ModelState.IsValid)
        //means user entered data correctly and is validated

    User u = new User() {Email = uvm.Email, Created = DateTime.Now};
    //How do I validate "u"?

    return View();
}

Should do something like this:

var results = new List<ValidationResult>();
var context = new ValidationContext(u, null, null);
var r = Validator.TryValidateObject(u, context, results);

What I am thinking is adding this validation technique in the base class (of business entity), and verify it when I am mapping from viewmodel class to business entity.

Any suggestions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T10:49:07+00:00Added an answer on May 23, 2026 at 10:49 am

    1) Use fluent validation on the model that the retrieves information from the user. it is more flexible then data annotation and easier to test.

    2) You might want to look into automapper, by using automapper you don’t have to write x.name = y.name.

    3) For your database model I would stick to the data-annotations.

    Everything below is based on the new information

    First and all you should place validation on both location like you did now for the actual model validation this is how I would do it. Disclaimer: this is not the perfect way

    First and all update the UserViewModel to

    public class UserViewModel
        {
            [Required()]
            [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$")]
            public String Email { get; set; }
        }
    

    Then update the action method to

            // Post action
            [HttpPost]
            public ActionResult register (UserViewModel uvm)
            {
                // This validates the UserViewModel
                if (ModelState.IsValid)
                {
    
                    try
                    {
                        // You should delegate this task to a service but to keep it simple we do it here
                        User u = new User() { Email = uvm.Email, Created = DateTime.Now };
                        RedirectToAction("Index"); // On success you go to other page right?
                    }
                    catch (Exception x)
                    {
                        ModelState.AddModelError("RegistrationError", x); // Replace x with your error message
                    }
    
                }       
    
                // Return your UserViewModel to the view if something happened               
                return View(uvm);
            }
    

    Now for the user model it gets tricky and you have many possible solutions. The solution I came up with (probably not the best) is the following:

    public class User
        {
            private string email;
            private DateTime created;
    
            public string Email
            {
                get
                {
                    return email;
                }
                set
                {
                    email = ValidateEmail(value);
                }
            }
    
            private string ValidateEmail(string value)
            {
                if (!validEmail(value))
                    throw new NotSupportedException("Not a valid email address");     
    
                return value;
            }
    
            private bool validEmail(string value)
            {
                return Regex.IsMatch(value, @"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$");
            }
    

    Last some unit test to check my own code:

       [TestClass()]
        public class UserTest
        {
    
            /// <summary>
            /// If the email is valid it is stored in the private container
            /// </summary>
            [TestMethod()]
            public void UserEmailGetsValidated()
            {
                User x = new User();
                x.Email = "test@test.com";
                Assert.AreEqual("test@test.com", x.Email);
            }
    
            /// <summary>
            /// If the email is invalid it is not stored and an error is thrown in this application
            /// </summary>
            [TestMethod()]
            [ExpectedException(typeof(NotSupportedException))]
            public void UserEmailPropertyThrowsErrorWhenInvalidEmail()    
           {
               User x = new User();
               x.Email = "blah blah blah";
               Assert.AreNotEqual("blah blah blah", x.Email);
           }
    
    
            /// <summary>
            /// Clears an assumption that on object creation the email is validated when its set
            /// </summary>
            [TestMethod()]
            public void UserGetsValidatedOnConstructionOfObject()
            {
                User x = new User() { Email = "test@test.com" };
                x.Email = "test@test.com";
                Assert.AreEqual("test@test.com", x.Email);
            }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Quick background: I'm programming in PHP, I have a domain model with a separate
I have 2 separate java services that use a complex type that is a
Say I have two separate classes, A and B. I also have Repository class
Given that I have a shell application and a couple of separate module projects
I know that mvvm calls for having a ViewModel class that wraps a Model
I have a viewmodel called ArticleAdmin that includes a list of checkboxes: public class
We say that model validation at controllers layer is the correct place to validate
In my MVC application I have a View Model that looks similar to this:
I have a simple model, consisting of a document that references one or more
How do you handle situations where you have Model classes based on SQL tables,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.