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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s