rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

jQuery Validator: Adding a No Space validation

Validate any kind of web forms using javascript/jQuery is a common practice. It prevents server side validation, although it is very important to implement it.

jQuery offers a great plugin for form validation: http://docs.jquery.com/Plugins/Validation. This plugin makes your validation easier than ever.

In some cases, you might not want to allow white spaces for specific fields, like password. Here's a quick code that will allow you to prevent white spaces for these type of fields.

jQuery code:

$(document).ready(function() {
  jQuery.validator.addMethod("noSpace", function(value, element) { 
    return value.indexOf(" ") < 0 && value != ""; 
  }, "Space are not allowed");

  $("#myform").validate({
    errorLabelContainer: $("#error"),
    rules: {
      password: { required: true, noSpace: true }
    },
    messages: {
      password: { required: 'Please enter your password' }
    }
  });

  $('#submit').click(function() {
    var valid = $("#myform").valid();
    if(!valid) {
      return false;
    }
    // other code
  });
});

HTML Code

<form action="#" method="post" id="myform">
<input name="email" id="email" type="text" placeholder="Your Email" />
<input name="password" id="password" type="password" placeholder="Password" />
<input type="button" value="submit" class="submit" />
</form>