Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to implement field validation using ASP.NET MVC? [closed]

I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.

like image 713
samiq Avatar asked Aug 19 '08 19:08

samiq


People also ask

How will you implement required field validator in MVC?

From the model class drop down, select "Employee" as the model. Click on the "Add" button. It will automatically create the view from the model. Add the "[Required]" attribute to the field that you want to make mandatory for insertion.

How is validation implemented in ASP.NET MVC?

Adding Validation to ModelThe validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation.

Which attribute can be used for data validation in MVC?

Answer is "DataAnnotations"


2 Answers

Take a look at the JQuery Validation plugin this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX.

Also a sample MVC controller method can be found here which basically uses the JsonResult action type like:

public JsonResult CheckUserName(string username) {     return Json(CheckValidUsername(username)); } 
like image 94
Daniel Pollard Avatar answered Oct 12 '22 01:10

Daniel Pollard


IMO using xVal with jQuery and DataAnnotationsModelBinder is the best combination.

Sometimes however, there are validation rules which cannot be checked entirely on the client side, so you need to use remote client-side validation.

I figured out way to generically implement remote client-side validation with xVal / jQuery.validate so that

  • Validation rules remain solely in your ASP.NET MVC model
  • You write each validation rule just once, and only in easily testable C# code. There is no JavaScript or other client-side counterpart .
  • There is no need to branch or otherwise modify xVal or jquery.validate
  • All you have to do for each new remote form validation rule is to derive from the base class shown in this article.

I wrote a blog article on this describing all the details.

like image 33
Adrian Grigore Avatar answered Oct 12 '22 01:10

Adrian Grigore