API based Custom FormValidation using SemanticUI/Jquery

In the last post, we discussed on how to implement form validation and subsequent submit using the Semantic UI and JQuery. In this follow up post, we discuss how we can enhance the validation capabilities further, by having a custom validation that depends on an external API call.

For the sake of example, let’s focus on an mock User Sign Up page, where we would be checking if the username exists prior to form submit.

Let’s write down our basic form first.

<form class="ui form" method='post' id="RegisterUser">
  <h4 class="ui dividing header">User Sign Up</h4>
  <div class="field">
    <div class="two fields">
      <div class="eight wide field">
        <label>UserName</label>
        <input type="text" placeholder="Username" id="username">
      </div>
    </div>
  </div>
  <button class="ui button" tabindex="0">Sign Up</button>
  <div class="ui hidden negative message" id="formresult"></div>
  <div class="ui error message" id="formvalidation"></div>
</form>

Now, let’s create our Validation Script.

var formvalidationrules = {
    on: 'submit',
    fields: {
      username: {
        identifier: 'username',
        rules: [{
          type: 'custom',
          prompt: 'username already exists'
        }]
      },
    },
    onSuccess: function(event) {
      event.preventDefault();
    }
  };

  $('#RegisterUser').form(formvalidationrules);

As you can see, the rule type has been specified as ‘custom’. The next obvious task is to write down the method to do the custom validation itself.

$.fn.form.settings.rules.custom = function() {
    var result;
    $.ajax({
      type: 'POST',
      url: '/echo/html/',
      async: false,
      data: {
        'html': $('#username').val()
      },
      success: function(data) {
        result = !(data == 'test');

      },
    });
    return result;

  };

Couple of things to note here.
a) The rule method has been added to form.settings.rules.
b) Now this is very important, your ajax calls needs to be synchronous.

That’s it, you are ready to roll. Check out the script in action in Fiddle Link

Advertisements

Form Validation and Submit using Semantic UI and JQuery

Bootstrap, despite all the effort to make it easily understandable, always relied heavily on its short hand notations for css classes. This seemed okay, until Semantic UI entered the race with its near perfect usage of natural language. The fact that it is well integrated with jQuery makes it a good choice for web developers.

One of the most common tasks in any web development has to do with form. The following code illustrates how to validate the form and submit it using the Semantic UI APIs.

 

                <form class="ui large form" method="POST" role="form" id="ValidateUser">
                    <section class="ui stacked segment">
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="user icon"></i>
                                @Html.TextBoxFor(a => a.UserName, new { placeholder = "UserName",id="username" })
                                @Html.ValidationMessageFor(a => a.UserName)
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                @Html.PasswordFor(a => a.Password, new { placeholder = "Password",id="password" })
                                @Html.ValidationMessageFor(a => a.Password)
                            </div>
                        </div>

                        <input id="submitbutton" class="ui submit fluid large green button" type="submit" value="Login"/> 
                        <!-- <div class="ui blue submit button">Submit</div> -->
                        <div class="ui hidden negative message" id="formresult"></div>
                        <div class="ui error message" id="formvalidation"></div>
                    </section>
                </form>
$(document).ready(function () {

            var urllink = '@Url.Action("Login", "Validation")';


            $('#ValidateUser').form(
                                     {
                                         on: 'blur',
                                         fields: {
                                             username: {
                                                 identifier: 'username',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Username cannot be empty'
                                                 }]
                                             },
                                             password: {
                                                 identifier: 'password',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Password cannot be emtpy'
                                                 }]
                                             }
                                         },
                                         onSuccess: function (event) {
                                             $('#formresult').hide();
                                             $('#formresult').text('');
                                             event.preventDefault();
                                             return false;
                                         }

                                     }
                                   )
                                 .api({
                                     url: urllink,
                                     method:'POST',
                                     serializeForm: true,
                                     data: new FormData(this),
                                     onSuccess: function (result) {
                                        $('#formresult').show();
                                        if (result.Success) {
                                            window.location = "/Dashboard/Dashboard";
                                        }
                                        else {

                                            $('#formresult').append(result.Msg);
                                        }
                                        return false;
                                    }
                    });


        });

Fix CORS in Firefox

CORS is a hated word anyone working on Web Solutions might have encountered if your website is accessing another website or API. So how do you ensure your website is able to the required URL ?

The first and easiest fix would be to include “Access Control” headers in your web.config.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 </customHeaders>
 </httpProtocol>

That should be it for every other browser except for Firefox, particularly if you are accessing a Restful Web API. By default, Firefox assumes the Request to have “Accept” Header as “application/xml“. This can be demonstrated once your fire up your Web API in Firefox Extension RestClient.

The workaround for the problem lies in changing the “Accept” header to “application/json”.

Exception Handling in Web API (Part 2): Exception Filter (Extended)

The Exception Filter implementation mentioned in the Part1 of the article is fairly simple and straightforward.  But as you start supporting more and more Exceptions, the Cyclomatic Complexity of the “OnException” method would increase because of the “if” condition nature.

A cleaner implementation of the Filter is shown below using Dictionary.

 public class DemoExceptionFilter : ExceptionFilterAttribute
 {
 public DemoExceptionFilter()
 {
 this.ExceptionDictionary = new Dictionary();
 this.ExceptionDictionary.Add(typeof(NotImplementedException), HttpStatusCode.ServiceUnavailable);
 this.ExceptionDictionary.Add(typeof(ArgumentOutOfRangeException), HttpStatusCode.BadRequest);
 }
 public IDictionary ExceptionDictionary
 {
 get;
 private set;
 }
 public override void OnException(HttpActionExecutedContext ExecutedContext)
 {

 if (ExceptionDictionary.ContainsKey(ExecutedContext.GetType()))
 {
 ExecutedContext.Response = new HttpResponseMessage(ExceptionDictionary[ExecutedContext.GetType()]);
 
 }
 else
 {
 throw new HttpResponseException( new HttpResponseMessage(HttpStatusCode.InternalServerError));
 }
 base.OnException(ExecutedContext);
 }

 }

Isn’t that cleaner ?
 

Exception Handling in Web API (Part 1): Exception Filter

The Web World, especially Web Services is fast moving towards the more abstract simpler Web API. This article is not focused on comparing Web Service and Web API, but rather it focuses on Exception Handling in Web API.

By default,  the most common exception that an API Controller raises are translated into an HTTP Status Code 500 (Internal Server Error) (HTTP Status Code ). But what if we want to customize the Error Code ? There are couple of ways to achieve it, the first part of this article focuses on Exception Filters.
An Exception Filter is probably the easiest way to handle the exception efficiently and it would handle any exception which the controller throws except for the HttpResponseException (Why HttpResponseException is not handled by Exception Filter will be discussed later).
The simplest way to create you own customized Exception Filter is to derive from ExceptionFilterAttribute Class under System.Web.Http.Filters namespace and override the OnException Method
An Example of Exception Filter is shown below.
public class DemoExceptionFilter : ExceptionFilterAttribute
{
public override void OnException( HttpActionExecutedContext ExecutedContext)
{
if (ExecutedContext.Exception is NotImplementedException)
{
ExecutedContext.Response = new HttpResponseMessage (HttpStatusCode.ServiceUnavailable);
ExecutedContext.Response.ReasonPhrase += " : Function Not Implemented";
}
base.OnException(ExecutedContext);
}
}
The code is pretty self explanatory. I have modified all the NotImlementedException to change the Http Status Code to 503 (Service Unavailable). I have also appended “Function Not Implemented”  message to the Reason Phrase . The next obvious step is to ensure our Exception Filter is used by the WebAPI Pipeline. To ensure that the DemoExceptionFilter is used globally, all we need to do is to add it to the list of filters in WebApiConfig. We use the Filters.Add Method in HttpConfiguration to do the same. For Example,
	public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Filters.Add(new ExceptionManagement.DemoExceptionFilter());
        }
That’s it !!!. Now every Exception your APIController throws , with the exception of HttpResponseException , would have to go through your DemoExceptionFilter. To test the code, I have thrown an exception from my controller as seen in example below.
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable  Get()
        {
            throw new NotImplementedException ();
        }

        // GET api/values/5
        public string Get( int id)
        {
            return "value" ;
        }
     }
     
Now run your application and check the response in Fiddler.
 NotImplemented
Wasn’t that easy ? Yes, but Exception Filters has its own short-comings, which would be explained in the next part. Happy Coding !!

Hello World in Ext JS and ASP.Net MVC4

Javascript based frameworks has been evolving of late and one of the prominent among them is External Javascript, better known as Ext JS. Unlike some of its competitors like Angular JS, Ext JS distinguishes itself with a rich suite of UI components. It is cross browser compatible. I am delving more into details of Ext JS, and as always, jumping right into the code.

For this post, we would be referring the online version of the ExtJS libraries.

Ok Tim to do some coding. Let’s start by creating a MVC application in Visual Studio.

image

Now open your ‘\Shared\_Layout.cshtml’ and add the following code in the ” section.

These lines refers and includes the CSS styles and ExtJS library. Like mentioned earlier in the post, we would be referring on-line version in this tutorial.  The next step is to add the script to call our Hello World Message box.

 

        Ext.onReady( function () {

            Ext.Msg.alert( “Alert” , “Hello world!” );

        });

 

Entire ‘ Section would look like

image

That’s it. You are done. Kick off the application and you will see your first application in ExtJS using Asp.Net

image