user1260970
user1260970

Reputation:

validations in ASP.Net MVC3

In MVC 3, it has DataAnnotations and also Custom Validation for validating on client side. But I can use Jquery or Javascript to write my own validation to a .js file. I mean I use the script tag and type=text/javascript. So which one should I use, the one in MVC3 or the other?

Upvotes: 0

Views: 57

Answers (2)

Garrett Fogerlie
Garrett Fogerlie

Reputation: 4458

As Mystere Man pointed out, just use MVC's data annotations as it does both client and server side validation.

Your question is a bit vauge, but based on your comment to Mystere Man I think you want to know how you can change the validation messages yourself? If so, you can overload @Html.ValidationSummary() with a message like

@Html.ValidationSummary(false, "My error message")

And on your models you can have a custom message for each of them by using an attribute like this:

[Required(ErrorMessage = "Please enter your name, this will not be displayed to others.")]
public string Name { get; set; }

You can also create custom validation, like a check box must be checked (since the [Required] attribute does not mean a bool must be true.) To do this and more, requires a bit more work but is very doable in the default validation.

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

MVC's data annotations use jquery validation on the client side. The point is that you use one method to do validation, and it works on both the server and the client.

You don't ever want to do only client-side validation, since a malicious attacker could bypass your javascript and send illegal values. client-side validation is a nice thing for users, but should never be used without server side validation.

MVC does both with data annotations, and you only have to deal with it in one place.

Upvotes: 1

Related Questions