Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 : Manually set the validation message from the server side

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??
 }
like image 602
TPaim Avatar asked Jul 19 '12 02:07

TPaim


People also ask

How do I validate server side?

The user input validation that takes place on the server side during a post back session is called server-side validation. The languages such as PHP and ASP.Net use server-side validation. Once the validation process on server side is over, the feedback is sent back to client by generating a new and dynamic web page.

What is client-side validation and server side validation?

When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side validation.

What is server side validation in C#?

Server-side validation helps prevent users from bypassing validation by disabling or changing the client script. Security Note: By default, ASP.NET Web pages automatically validate that malicious users are not attempting to send script or HTML elements to your application.

What is server side validation in MVC?

Server side validations are required for ensuring that the received data is correct and valid. If the received data is valid then we do the further processing with the data. Server side validations are very important before playing with sensitive information of a user.


1 Answers

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.

like image 128
Nate Avatar answered Sep 20 '22 10:09

Nate