MVC4 : Manually set the validation message from the server side

Someone asked on Stack Overflow:

I want to validate some form fields in the server side, but I don’t want to use Data Annotations Custom Validators. I need to manually set its value based on the return of the called Business Layer Method to define this message.

Just as an example!

NEED:

If the given username already exists, the MVC4 validation error span shall display “This username already exists.”

CODE:

 if (_business.UserNameExists(username))
 {
    // Set the field validation error span message
    // HOW TO DO??
 }

I posted the following answer, which was chosen as the accepted answer and received 15 upvotes:

A friend came with the solution, it is very simple!

 if (_business.UserNameExists(username))
 {
    // Set the field validation error span message
    ModelState.AddModelError("UserName", "This username already exists.");
 }

Where UserName is the name of the Entity attribute being validated.


Originally posted on Stack Overflow — 15 upvotes (accepted answer). Licensed under CC BY-SA.

signed letter b

Dad. Geek. Gamer. Software developer. Cloud user. Old Car enthusiast.  Blogger.


Top Posts


profile for Nate on Stack Exchange, a network of free, community-driven Q&A sites
a proud member of the blue team of 512KB club
Thoughts, opinions, and ideas shared here are my own. © 2026 Nate Bross.