Rune Grønkjærs Blog
Abonnér på mit feed

Javascript jQuery form validation

Client side validation of forms is often something something we struggle with in Dynamicweb. Dynamicweb default form validation has one option and that is: should the box be filled out or not. With the plugin I have written, we get some more opportunities to validate our forms. My jQuery form validation plugin, is based on our needs in Dyanmicweb, but it can easily be used for other html forms as well.

The form

Below is a typical example of a Dynamicweb form. It is extremely simple and does not contain IDs of the input fields. This means that we don’t have much to go for when selecting them with jQuery. For illustration purposes, I have chosen to omit a portion of the Dynamicweb html. After the form html I have pasted a simple Dynamicweb javascript with which to validate selected fields. This javascript only validates for the existense of text. Often we need to check if the user enters a valid email, date or even a number.

Dynamicweb formscript

  function onFormSubmit() {
  if (document.Form1.elements["input1"].length) {
    for (i = 0; i < document.Form1.elements["input1"].length; i++) {
      if (document.Form1.elements["input1"][i].value.length <= 0) {
        document.Form1.elements["input1"][i].focus();
        alert('input1 must be filled out!');
        return false;
      }
    }
  }
  else {
    if (document.Form1.elements["input1"].value.length <= 0) {
      document.Form1.elements["input1"].focus();
      alert('input1 must be filled out!');
      return false;
    }
  }
  document.Form1.action = "/Admin/Public/FormMail.aspx?mode=20";
  document.Form1.submit();
}

Dynamicweb form

<form id="Form1" action="" onsubmit="return onFormSubmit()">
<div>
  <input name="input1" value="blah" />
  <input name="input2" value="1234" />
  <input name="input3" value="rune@gronkjaer.dk" />
  <input name="input4" value="" />
  <input name="input5" value="12345" />
  <input name="input6" value="12 01 2010" />
  <input name="submit" type="submit" value="submit" />
</div>
</form>

My solution

My solution takes into account the Dynamicweb forms own submit javascript, wich I run if the the form passes my jQuery form validation plugins criterias.

Below I have created a test setup of how the plugin can be used for the above form setup.
The plugin is started in the document ready event that fires after the browser has read the document through.

Using the jQuery validation plugin

jQuery(function() {
  /*
  valArr is a collection of validations to be run on one or more forms.
  It is not necessarily all validations that is to be run on the same form
  The plugin will test whether the form contains the selected fields.
  The order in the sub table is: 
  - validation type
  - select css to frame the box
  - error message
  - a number of extra parameters (determined by the validation type)
  */
  var valArr = [["isalphanumeric", "[name=input1]", "input1 must be letters"],
                ["isNumeric", "[name=input2]", "input2 must be a number"],
                ["isMail", "[name=input3]", "input3 must be an email"],
                ["notempty", "[name=input4]", "input4 must be filled out"],
                ["isLength", "[name=input5]", "input5 must be 5 characters", 5],
                ["isDate", "[name=input6]", "input6 must be a date"]],
      /*
      settings must be sent passed as a parameter in ReadyValidate 
      method when you make one or more forms ready for validation
      */
      settings = {
        //Type function
        //If the validation fails this event is fired
        onValidateFalse: fail,
        //Type function
        //If the validation succeeds this event is fired
        onValidateTrue: yessir,
        //Validation parameters
        valArr: valArr
      };
  /*
  With jQuery you select one or more forms.
  Then ReadyValidate is called on the jQuery collection
  Our setting is passed alling
  Now the form is ready and will be validated when submitted.
  */
  jQuery("#Form1").ReadyValidate(settings);
});

function fail() {
  alert("fail");
}

function yessir() {
  alert("yes sir");
}

The jQuery form validation plugin

Below I have pasted the code for my jQuery plugin. It is binary and consists of a jQuery extension, and a validation class with a series of static validation methods.
The validate class can be used for validations outside the plugin. The plugin is full of comments explaining it's use.
jQuery.fn.ReadyValidate = function(settings) {
  //Extending the settings
settings = jQuery.extend({
    //Type function
    //If the validation fails this event is fired
    onValidateFalse: null,
    //Type function
    //If the validation succeeds this event is fired
    onValidateTrue: null,
    //Validationparameters
    valArr: null
  }, settings);
  //If any forms have been selected the javascript continues
  if (this[0]) {
    //Each form treated independently.
    //This means that it is possible to handle multiple forms on same page.
    this.each(function() {
      //The form's own submit event is saved
      var submit = this.onsubmit,
          //The form is jQueryfied
          jQform = jQuery(this);
      //The forms own submit event is removed
      //This will give us full control later in the process
      this.onsubmit = null;
      //We tie our own event to the form's onSubmit
      jQform.bind("submit", function() {
        /*
        Once the form submits the following will be run.
        The Validation array is traversed
        and for each item we search the form
        for matching elements.
        */
        var invalids = [];
        for (var i = 0; i < settings.valArr.length; i++) {
          var eleArr = settings.valArr[i],
              valType = eleArr[0].toLowerCase(),
              str = jQform.find(eleArr[1]).val()
          isValid = true;
          /*
          Here the Validate class is used to check
          on field validation. As the validation array
          contains the string names of the corresponding
          validation method, we can find the method.
          */
          isValid = Validater[valType](str, eleArr[3] ? eleArr[3] : null, eleArr[4] ? eleArr[4] : null);
          if (!isValid) {
            invalids.push(eleArr);
          }
        }
        //Checking if some fields failed validation
        if (invalids.length == 0) {
          //If no fields failed, firing onValidateTrue
          //but only if it contains a method
          if (settings.onValidateTrue) { settings.onValidateTrue(this); }
          //If the form had a submitmetode
          //signed up this is fired here. 
          //Otherwise we just return true
          //wich will make the form send it's
          //content to the server
          if (submit) {
            return submit(this);
          } else {
            return true;
          }
        }
        //If the script reaches this point, one or more
        //fields failed validation
        var errorTxt = "";
        //We run through the failed fields and a
        //full validationtext is created
        for (var i = 0; i < invalids.length; i++) {
          errorTxt += invalids[i][2] + (i < invalids.length - 1 ? "\n" : "");
        }
        //The validationtekst is alerted and onValidateFalse is fired
        alert(errorTxt);
        if (settings.onValidateFalse) { settings.onValidateFalse(this); }
        return false;
      });
    });
  }
  return this;
};

/*
Validater is a class with only static methods
*/
Validater = {
  // returns true if it is a genuine email
  ismail: function(str) {
    var t = "\\wáàãââæåçéèêëìíîïñòóôõöøùúûüýÿ";
    var regexp = new RegExp("^[" + t + "][" + t + "\\.\\-]*@[" + t + "][" + t + "\\.\\-]*\\.[a-z]{2,6}$", "i");
    if (!this.notempty(str) || !regexp.test(str) || /(\.@|\-@|@\.|@\-|\-\-|\.\.|\-\.|\.\-)/g.test(str)) { return false; }
    return true;
  },
  // returns true if the phone number is correct
  isphonenumber: function(str) {
    if (this.notempty(str) || !str.match(/^[0-9]{8}$/)) {
      return false;
    }
    return true;
  },
  // returns true if the string is not empty
  notempty: function(str) {
    return (str !== null) && (str.length > 0);
  },
  // returns true if the string contains only these characters AZ or a-Z
  // Special characters can be added as well. In this case I added some
  // special danish characters
  isalpha: function(str) {
    var re = /[^a-zA-ZæøåÆØÅ]/g;
    if (re.test(str)) { return false; }
    return true;
  },
  // returns true if the string contains only numbers from 0-9
  isnumeric: function(str) {
    var re = /[\D]/g;
    if (re.test(str)) { return false; }
    return true;
  },
  // returns true if the string contains only these characters or numbers:
  // A-Å, a-å or 0-9
  isalphanumeric: function(str) {
    var re = /[^a-zA-Z0-9æøåÆØÅ]/g;
    if (re.test(str)) { return false; }
    return true;
  },
  // returns true if the strings length is exactly "len"
  islength: function(str, len) {
    return str.length === len;
  },
  // returns true if the strings length is between "min" and "max"
  islengthbetween: function(str, min, max) {
    return (str.length >= min) && (str.length <= max);
  },
  // returns true if the string is a date in one of the formats:
  // mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
  // dd mm yyyy, dd/mm/yyyy, dd.mm.yyyy, dd-mm-yyyy
  isdate: function(str, monthFirst) {
    var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/;

    if (!re.test(str)) { return false; }
    var result = str.match(re);
    var d = parseInt(result[1]);
    var m = parseInt(result[2]);
    var y = parseInt(result[3]);
    if (monthFirst) {
      var m = parseInt(result[1]);
      var d = parseInt(result[2]);
      var y = parseInt(result[3]);
    }
    if (m < 1 || m > 12 || y < 1900 || y > 2100) { return false; }
    if (m === 2) {
      var days = ((y % 4) === 0) ? 29 : 28;
    } else if (m === 4 || m === 6 || m === 9 || m === 11) {
      var days = 30;
    } else {
      var days = 31;
    }
    return (d >= 1 && d <= days);
  },
  // returns true if "str1" is the same as "str2"
  ismatch: function(str1, str2) {
    return str1 === str2;
  },
  // returns true if the string contains only white spaces.
  // Can not check a password type input for whitespace
  iswhitespace: function(str) {
    var re = /[\S]/g;
    if (re.test(str)) { return false; }
    return true;
  },
  // returns true if the demands of the custom check is met
  customcheck: function(str, re) {
    if (re.test(str)) { return false; }
    return true;
  }
};

Example

Try changing some of the texts below. By default, all of them validates true.
I have chosen to change a bit on the script, so the form never submits true, to make testing quicker (No postback)
This post was written in Array, Date, Javascript, jQuery, Plugin, regexp. Ad permalink to favorites. Follow all comments with RSS feed for this posts. Drop a comment or a trackback: Trackback URL. | Læs denne side på dansk dansk version

4 comments

  1. Written August 8, 2010 at 5:36 pm | Permalink

    tara reid body nude http://www.gamezebo.com/members/tara-reid-nude tara reid my boss’s daughter nude

  2. Written August 8, 2010 at 7:45 pm | Permalink

    free Montana Fishburne sex clips http://www.apocalyptica.com/us/node/2958 Montana Fishburne sex vid free

  3. Written August 8, 2010 at 8:54 pm | Permalink

    miley cyrus scandal fakes http://www.ozzy.com/us/blog/miley-cyrus-fakes sexy whore miley cyrus porn fakes

  4. Written May 8, 2011 at 8:14 am | Permalink

Drop a comment

Your email is never published nor shared. Required fields are marked *

*
*

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Dansk version