SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Zealot
    Join Date
    Nov 2007
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simply javascript - form validation problem

    Hello!
    I'm Zoran, and this is my first post at this site.

    I'm a verry begginer javascript programmer, and I'm learning it after simply javascript book (by sitepoint). I came to chapter 6 of this book, where there is example of how to make "reusable form validation". Here's the code from the book(I hope it's not illegal to post this code since it's from a book) :

    http://rafb.net/p/Y2eHpW96.html

    The problem is, that I don't quite understand the "rules" and the "errors" codes. What are both? Are they some sort of subclass? in this book it usually declares object like this:

    var ObjectName={
    ...
    };

    so I don't know why does it use this sintaxs:
    errors:{...}.
    I haven't seen this sort of object declaration so if anybody could explain how this works, I'd be verry happy.

    oh, and also the variables or whatever they are inside them, like "required", "requiredNotWhitespace","positive integer" (if you see the code in the link), can you explain that too?

    Cheers,
    Zoran

  2. #2
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,227
    Mentioned
    194 Post(s)
    Tagged
    2 Thread(s)

    syntax

    Hi Zocky, welcome to the forums,
    "rules" and "errors" are arrays. They are used by submitListener()
    HTML Code:
    .....
            var rule = FormValidation.rules[oneClass];
            if (typeof rule != "undefined")
            {
              if (!rule.test(fields[i].value))
              {
                fields[i].focus();
                alert(FormValidation.errors[oneClass]);
    .....
    HTML Code:
      rules:
      {
        required: /./,
        requiredNotWhitespace: /\S/,
        positiveInteger: /^\d*[1-9]\d*$/,
        positiveOrZeroInteger: /^\d+$/,
        integer: /^-?\d+$/,
        decimal: /^-?\d+(\.\d+)?$/,
        email: /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/,
        telephone: /^(\+\d+)?( |\-)?(\(?\d+\)?)?( |\-)?(\d+( |\-)?)*\d+$/
      },
    For example, when you give something (ie. an input) a class="requiredNotWhitespace", the code will check to see if it matches the regex for "not whitespace", if it does not match, the code will use the error message from the errors array
    HTML Code:
      errors:
      {
        required: "Please fill in this required field.",
        requiredNotWhitespace: "Please fill in this required field.",
        positiveInteger: "This field may only contain a positive whole number.",
        positiveOrZeroInteger: "This field may only contain a non-negative whole number.",
        integer: "This field may only contain a whole number.",
        decimal: "This field may only contain a number.",
        email: "Please enter a valid email address into this field.",
        telephone: "Please enter a valid telephone number into this field."
      },
    in this case, "Please fill in this required field."

  3. #3
    SitePoint Zealot
    Join Date
    Nov 2007
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    tnx for reply!

    hm, if they are arrays, how come they are not in this style:
    var my_cars= new Array()
    my_cars["cool"]="Mustang";
    my_cars["family"]="Station Wagon";
    my_cars["big"]="SUV";

    I never saw using "colons" but rether something like above. IS this basicly the same thing?

    --edited--
    oh, and btw, this is associative array?

  4. #4
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,227
    Mentioned
    194 Post(s)
    Tagged
    2 Thread(s)

    javascript arrays

    Yes, the array syntax isn't that common I guess, but it is one way to do it.
    The array keys are the value of the "oneClass" variable, which is the class of the input.
    HTML Code:
       submitListener: function(event)
      {
        var fields = this.elements;
     
        for (var i = 0; i < fields.length; i++)
        {
          var className = fields[i].className;
          var classRegExp = /(^| )(\S+)( |$)/g;
          var classResult;
     
          while (classResult = classRegExp.exec(className))
          {
            var oneClass = classResult[2];
            var rule = FormValidation.rules[oneClass];
    So it is an associative array, and AFAIK you could do it like
    HTML Code:
    var rules = new Array();
    rules['required'] = "/./,";
    rules['requiredNotWhitespace'] = "/\S/,";
    rules['positiveInteger'] = "/^\d*[1-9]\d*$/";
    if you wanted to. Just that the array_name:{key: value} syntax is less verbose.

  5. #5
    SitePoint Zealot
    Join Date
    Nov 2007
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I see. Tnx a lot for help!

    --edited--
    hm, in book, it later says that "errors" and "rules" are actually objects, and inside it it has properties (I did see property being used in with this syntax( varName: value1, varName2: value2,....), i think it's called object literal syntax, so I get this part, but I don't get part about those two (errors, rules), being objects. even in the book where it does usually use object literal, it does it this way:

    var Robot =
    {
    metal: "Titanium",
    killAllHumans: function()
    {
    alert("Exterminate!");
    }
    };

    while in my case, in my first post, rules and errors looks rether like this:
    Robot :
    {
    metal: "Titanium",
    killAllHumans: function()
    {
    alert("Exterminate!");
    }
    };
    So, any ideas?
    Last edited by Zocky; Nov 22, 2007 at 08:54.

  6. #6
    SitePoint Zealot
    Join Date
    Nov 2007
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if it's of any help to you, first, in book it say this:

    To build a reusable form validation script, we can bundle all of the regular expressions we’ve seen so far into a JavaScript object: (meaning rules)

    Then, at the end, he says this:
    Remember that we’ve stored all of our validation expressions as properties of
    the FormValidation.rules object. Usually, you access the property of an object
    using a dot and the property name (for example,
    FormValidation.rules.required), but we can’t do that if the name of the
    property is stored as a string in a variable, as it is now. If we typed
    FieldValidation.rules.oneClass, JavaScript would actually look for a property named oneClass, rather than using the name stored in the oneClass
    variable.
    The trick to accessing a property using a property name that’s stored in a variable
    is to treat the object like an array, and use the property name as the array
    index. So we can fetch the regular expression for a particular class using
    FormValidation.rules[oneClass].

    FRom what I see, "rules" and "errors" are object, but are treated as arrays because you can't access it's property if name is saved in variable. But still, why using syntax object:{...} instead of var object ={...} ?

  7. #7
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,227
    Mentioned
    194 Post(s)
    Tagged
    2 Thread(s)

    oop

    I would think an object property value would be accessed like rules->required, not rules['required'], but I'm still a bit of an OOP newbie myself, so I find the terminology a bit confusing at times too. For example, why is a function inside a class a method? Why are variables inside a class properties? To be technically correct, you will be better off using the books terminology, as I'm sure it's more correct than mine. I don't know if the "var object" syntax would work, but I imagine it would. You could try copying the code into a file using the alternative syntax to see if it works. If it does, you can decide which syntax you like better (personal comfort vs. less verbose). But I imagine that after you work with it written like that for a while, you'll become more comfortable with it.

  8. #8
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,227
    Mentioned
    194 Post(s)
    Tagged
    2 Thread(s)

    update

    Well, I've learned something new (I may just get OOP yet). This thread should enlighten http://www.sitepoint.com/forums/showthread.php?t=517746


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •