Using manually the ASP.NET MVC’s client side validation infrastructure

Using manually the ASP.NET MVC’s client side validation infrastructure

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. ASP.NET MVC client side validation is based on the jQuery validation plugin. It can be said that MVC’s client-side validation is an opinionated version of how jQuery validation should work in an ASP.NET MVC project. Despite this, the underlying implementation is fully based on jQuery’s. In this blog post I’ll show you how you can take advantage of this.

mvc

ASP.NET MVC Client Side validation requirements

First, here’s the list of things you need to do to enable client-side validation in an ASP.NET MVC project Make sure your client side code is loading both:

  • jquery.validate.js
  • jquery.validate.unobtrusive.js

Make sure your web.config has the following keys in appSettings with the follwoing values:

These settings can be overridden in a controller, make sure that is not happening. For example this would turn off client side validation if executed inside a controller’s action:

The next requirement is that you use attributes from System.ComponentModel.DataAnnotations in the Model class that is used in view where you want client-side validation enabled.

For example, if we want the Email field to be a valid email, and make the password and email fields required we would create a model like this:

Finally, we have to use the HtmlHelpers that generate the correct markup for all of this to work, and they have to be inside a form, for example

Getting away with using Client Side validation without a model

The last two requirements are actually optional. It is possible to take advantage of client side validation without having to create a model class and annotate it, which can be useful if you only use a couple of parameters (such as in the Login example).

If you inspect the markup that the helpers generate you’ll see that it’s actually pretty simple:

It turns out that to enable client side validation without using the HtmlHelpers and a model you just have to add an input with data-val="true" and then data-val- followed by validation method that you want to apply (e.g. data-val-required), the value of which will be the error message presented to the user (e.g. data-val-required="This is the error message"). This works because the MVC’s “unobtrusive validation” works by looking for inputs that are annotated with data-val attributes.

The data-valmsg-for‘s value is the name (not the id) of the input it refers to, and data-valmsg-replace="true" just means that the default message should be replaced, for example you could have a default message for the email field:

This message would then be replaced by any validation error that occurs in the email field, for example “The email is required”. If data-valmsg-replace="false" then the original message will never be replaced. The only consequence of an error is that the span’s class is changed from field-validation-valid to field-validation-error (this happens irrespectively of the value of data-valmsg-replace="false").

Some validation methods have parameters, for example RegularExpression. The way these work is very similar, they just need additional data-val- for their parameters. If you want to validate a text field using a regular expression for 5 to 8 digits, it would look like this:

If you create the markup yourself you can get away without having to create a model for your view. Using the login example from above, your controller action for handling the user logging in could simply be:

You’d have to make any server-side checks on the parameters yourself though.

Here is the list of the System.ComponentModel.DataAnnotation attributes you can use, and their data-val counterparts:

  • Compare
    • data-val-equalto="Error message"
    • data-val-equalto-other="The name of the other field"
  • CreditCard
    • data-val-creditcard="Error message"
  • EmailAddress
    • data-val-email="Error message"
  • MaxLength
    • data-val-maxlength="Error message"
    • data-val-maxlength-max="Maximum length (e.g. 5)"
  • MinLength
    • data-val-minlength="Error message"
    • data-val-minlength-min="Minimum length (e.g. 2)"
  • Range
    • data-val-range="Error message"
    • data-val-range-max="Max value"
    • data-val-range-min="Min value"
  • RegularExpression
    • data-val-regex="Error message"
    • data-val-regex-pattern="The regular expression (e.g. ^[a-z]+$)"
  • Required
    • data-val-required="Error message"
  • StringLength
    • data-val-length="Error message"
    • data-val-length-max="Maximum number of characters"

There are also a few validation methods you can use that don’t seem to have a counterpart in System.ComponentModel.DataAnnotation. In fact you get a list of all the available client side validation methods by typing (for example in chrome) dev tools console: $.validator.unobtrusive.adapters. Here’s the list of the ones that don’t have a matching attribute: date, digits, number, url, length, remote, password.

Securing your ASP.NET MVC Application

Securing your ASP.NET MVC Application

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one’s web application.

By decorating the HomeController using the Authorize attribute (notice I didn’t specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there’s security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

Lastly, add the following to the project’s web.config file:

as