SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Sep 2002
    Posts
    225
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JavaScript form validation "Best Practices"?

    I'm a newb when it comes to JS but I know enough to write some validation scripts and a little AJAX. However, my scripts are usually pretty long and I know it has got to be easier than I'm making it. I was wondering if you all had any "Best Practices" that you could pass on so I can become a better JS programmer. Thanks!

    p.s. my long long script is below for your enjoyment!

    PHP Code:
    // JavaScript Document
    // doesn't entirely work yet.
    window.onload setup_validation;
    var 
    theForm;
    var 
    submitBtn;
    var 
    xhr false;
    var 
    tm_first_name false;
    var 
    tm_last_name false;
    var 
    region false;
    var 
    store false;
    var 
    date false;
    var 
    month '';
    var 
    day '';
    var 
    year '';
    var 
    month_name = new Array(12);

    function 
    setup_validation() {
        if (
    document.getElementById) {
            
    month_name[1] = 'January';
            
    month_name[2] = 'February';
            
    month_name[3] = 'March';
            
    month_name[4] = 'April'
            
    month_name[5] = 'May';
            
    month_name[6] = 'June';
            
    month_name[7] = 'July';
            
    month_name[8] = 'August';
            
    month_name[9] = 'September';
            
    month_name[10] = 'October';
            
    month_name[11] = 'November';
            
    month_name[12] = 'December';
            
            
    //fieldArray.length = 0;
            //errorMsg = document.getElementById("error");
            
    theForm document.getElementById("theForm");
            
    theForm.onsubmit = function() { return validate_form(); }
            var 
    0;
            for (var 
    i=0i<theForm.lengthi++) {
                
    //alert(theForm.elements[i].id);
                //document.getElementById('IDVal').innerHTML += i + ' ' + theForm.length + ' ' + theForm.elements[i].name + ' ' + theForm.radio + '<br>';
                
    switch (theForm.elements[i].id) {
                    case 
    "tm_first_name":
                        
    theForm.elements[i].onchange validate_field;
                        
    theForm.elements[i].onblur validate_field;
                        
    theForm.elements[i].value '';
                        break;
                    case 
    "tm_last_name":
                        
    theForm.elements[i].onchange validate_field;
                        
    theForm.elements[i].onblur validate_field;
                        
    theForm.elements[i].value '';
                        break;
                    case 
    "store":
                        var 
    storeOptionNode document.createElement('option');
                        
    storeOptionNode.setAttribute('value''store');
                        
    storeOptionNode.setAttribute('selected''selected');
                        
    storeOptionNode.setAttribute('id''storeOption');
                        
    storeOptionNode.innerHTML 'Select a Store';
                        
    theForm.elements[i].appendChild(storeOptionNode);

                        
    theForm.elements[i].onchange remove_store_option;
                        
    theForm.elements[i].disabled true;
                        break;
                    case 
    "region":
                        var 
    regionOptionNode document.createElement('option');
                        
    regionOptionNode.setAttribute('value''region');
                        
    regionOptionNode.setAttribute('selected''selected');
                        
    regionOptionNode.setAttribute('id''regionOption');
                        
    regionOptionNode.innerHTML 'Select a Region';
                        
    theForm.elements[i].appendChild(regionOptionNode);
                        
                        
    theForm.elements[i].onchange remove_region_option;
                        break;
                    case 
    "date_month":
                        var 
    currentDate = new Date();
                        var 
    currentDateNode document.createElement('option');    
                        var 
    tempDate currentDate.getMonth()+1;

                        
    currentDateNode.setAttribute('value'tempDate);
                        
    currentDateNode.setAttribute('selected''selected');
                        
    currentDateNode.setAttribute('id''month_current');
                        
    currentDateNode.innerHTML tempDate ' (' month_name[tempDate] + ')';
                        
    theForm.elements[i].appendChild(currentDateNode);
                        
                        
    theForm.elements[i].onchange validate_field;
                        break;
                    case 
    "date_day":
                        var 
    currentDate = new Date();
                        var 
    currentDateNode document.createElement('option');    
                        var 
    tempDate currentDate.getDate();
                        
                        
    currentDateNode.setAttribute('value'tempDate);
                        
    currentDateNode.setAttribute('selected''selected');
                        
    currentDateNode.setAttribute('id''day_current');
                        
    currentDateNode.innerHTML tempDate;
                        
    theForm.elements[i].appendChild(currentDateNode);
                        
                        
    theForm.elements[i].onchange validate_field;                    
                        break;
                    case 
    "date_year":
                        var 
    currentDate = new Date();
                        var 
    currentDateNode document.createElement('option');    
        
                        
    currentDateNode.setAttribute('value'currentDate.getFullYear());
                        
    currentDateNode.setAttribute('selected''selected');
                        
    currentDateNode.setAttribute('id''year_current');
                        
    currentDateNode.innerHTML currentDate.getFullYear();
                        
    theForm.elements[i].appendChild(currentDateNode);
                        
                        
    theForm.elements[i].onchange validate_field;                    
                        break;
                    default:

                        break;
                }
            }
            
    //alert(radioBtns_group[0]);
            //alert(j);
        
    }
        return 
    false;
    }

    function 
    remove_region_option() {
        if (
    document.getElementById('regionOption')) {
            
    this.removeChild(document.getElementById('regionOption'));
        }
        
        
    // AJAX request to build store list based off of region picked
        
    try {
            
    xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (
    e) {
            try {
                
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (
    e2) {
                
    xhr false;    
            }
        }
        
        if (!
    xhr && typeof XMLHttpRequest != 'undefined') {
            
    xhr = new XMLHttpRequest();
        }

        if (
    xhr) {
            
            
    //xhr.setRequestHeader("Cache-Control","no-cache");
            //xhr.setRequestHeader("Cache-Control","must-revalidate");
            //xhr.setRequestHeader("Cache-Control","no-store");
            //xhr.setRequestHeader("Pragma","no-cache");
            //xhr.setRequestHeader("Expires","0");
            //xhr.overrideMimeType("text/xml");
            
    xhr.onreadystatechange build_store_option;
            
    xhr.open("GET"'includes/get_stores.php?region_id=' this.valuetrue);
            
    xhr.send(null);
        } else {
            
    // error
            
    alert('There was an error! Please try again in a few seconds.');
        }
        
        
    region true;
        
    document.getElementById('store').disabled false;
        return 
    false;
    }

    function 
    build_store_option() {
        if (
    xhr.readyState == 4) {
            if (
    xhr.status == 200) {
                if (
    xhr.responseXML && xhr.responseXML.contentType == "text/xml") {
                    var 
    outMsg xhr.responseXML.getElementsByTagName('store');//[0].textContent;
                    
    var mLength xhr.responseXML.getElementsByTagName('store').length;
                } else {
                    var 
    outMsg xhr.responseText;
                    var 
    mLength 0;
                }
            } else {
                var 
    outMsg "there was a problem with the request " xhr.status;
            }
            
            var 
    stores document.getElementById('store');
            
            while (
    stores.hasChildNodes()) {
                
    stores.removeChild(stores.firstChild);    
            }
            
    //alert(outMsg);
            //alert(xhr.responseXML.getElementsByTagName('store').length);
            
    if (mLength 0) {
                for (var 
    0xhr.responseXML.getElementsByTagName('store').lengthi++) {
                    
    //alert(xhr.responseXML.getElementsByTagName('id')[i].textContent);
                    
    var storeOptionNode document.createElement('option');
                    
    storeOptionNode.setAttribute('value'xhr.responseXML.getElementsByTagName('id')[i].textContent);
                    
    storeOptionNode.innerHTML xhr.responseXML.getElementsByTagName('name')[i].textContent;
                    
    stores.appendChild(storeOptionNode);
                }
            } else {
                var 
    tempArray outMsg.split(';');
                for (var 
    0tempArray.lengthi++) {
                    var 
    storeOptionNode document.createElement('option');
                    
    storeOptionNode.setAttribute('value'tempArray[i]);
                    
    storeOptionNode.innerHTML tempArray[++i];
                    
    stores.appendChild(storeOptionNode);
                    
                }
            }
            
            var 
    storeOptionNode document.createElement('option');
            
    storeOptionNode.setAttribute('value''store');
            
    storeOptionNode.setAttribute('selected''selected');
            
    storeOptionNode.setAttribute('id''storeOption');
            
    storeOptionNode.innerHTML 'Select a Store';
            
    stores.appendChild(storeOptionNode);
            
        }

        return 
    true;
    }

    function 
    remove_store_option() {
        if (
    document.getElementById('storeOption')) {
            
    this.removeChild(document.getElementById('storeOption'));
        }
        
    store true;
        return 
    true;
    }

    function 
    validate_field() {
        switch (
    this.id) {
            case 
    "tm_first_name":
                if (!
    check_name(this.value)) {
                    
    tm_first_name false;
                    return 
    false;
                } else {
                    
    tm_first_name true;
                }
                break;
            case 
    "tm_last_name":
                if (!
    check_name(this.value)) {
                    
    tm_last_name false;
                    return 
    false;
                } else {
                    
    tm_last_name true;
                }
                break;
            case 
    "date_month":
                if (!
    check_date(this.value,  document.getElementById('date_day').valuedocument.getElementById('date_year').value)) {
                    
    date false;
                    return 
    false;
                }
                
                
    date true;
                
                break;
            case 
    "date_day":
                if (!
    check_date(document.getElementById('date_month').valuethis.valuedocument.getElementById('date_year').value)) {
                    
    date false;
                    return 
    false;
                }
                
                
    date true;
                
                break;
            case 
    "date_year":
                if (!
    check_date(document.getElementById('date_month').valuedocument.getElementById('date_day').valuethis.value)) {
                    
    date false;
                    return 
    false;
                }
            
                
    date true;
                
                break;
        }
        
        return 
    true;
    }

    function 
    isString(string) {
        var 
    re = /^[a-z-\.,]+$/i;
        
    string.split(" ");
        for (var 
    i=0is.lengthi++) {
            if (!
    re.test(s[i])) {
                return 
    false
            }
        }
        return 
    true;    
    }

    function 
    isInteger(integer) {
        var 
    re = /^[\d]+$/;
        if (!
    re.test(integer)) {
            return 
    false
        }
        return 
    true;
    }

    function 
    check_name(tmname) {
        if (!
    isString(tmname)) {
            return 
    false;
        }
                
        return 
    true;
    }

    function 
    check_tmid(tm_id) {
        if (!
    isInteger(tm_id)) {
            return 
    false;
        }
                
        return 
    true;
    }

    // does nothing yet
    function check_date(monthdayyear) {
        return 
    true;
    }

    function 
    is_empty(aTextField) {
        if ((
    aTextField.value.length==0) || (aTextField.value==null)) {
            return 
    true;
           }

        return 
    false;
    }

    // checks to make sure that all fields have a value
    // if so then enable the submit button.
    function check_form() {
        var 
    error false;
        var 
    errorMsg '';
        
    //document.getElementById('nameVal').innerHTML += document.getElementById('theForm').length + ' anything?<br>';
        //var count = document.getElementById('theForm').length;
        //var Form = document.getElementById('theForm');
        
        
    if (!tm_first_name) {
            
    errorMsg += '- Please fill in a correct first name.\n';
            
    error true;
        }
        
        if (!
    tm_last_name) {
            
    errorMsg += '- Please fill in a correct last name.\n';
            
    error true;
        }
        
        if (!
    region) {
            
    errorMsg += '- Please select a Region.\n';
            
    error true;
        }
        
        if (!
    store) {
            
    errorMsg += '- Please select a Store.';
            
    error true;
        }
        
        if (!
    date_month) {
            
    errorMsg += '- Please insert a correct month.';
            
    error true;
        }
        
        if (!
    date_day) {
            
    errorMsg += '- Please insert a correct day.';
            
    error true;
        }
        
        if (!
    date_year) {
            
    errorMsg += '- Please insert a correct year.';
        }
        
        if (
    error) {
            
    alert(errorMsg);
            return 
    false;
        }
        
        
    // else enable submit button
        
    return true;    
    }

    function 
    validate_form() {
        if (!
    check_form()) {
            return 
    false;
        }
        return 
    true;


  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    1) Instead of this:
    Code:
    var month_name = new Array(12);
    do this:
    Code:
    var month_name = []; //empty "array literal"
    That is similar to doing this:

    var arr = [1, 2, 3];

    The thing on the right is known as an "array literal", which distinguishes it from an array variable, which is what 'arr' is. A similar concept applies to strings:

    var str = "hello";

    'str' is a variable and "hello" is a string literal. str is variable so it's value can change(i.e. vary) but "hello" is not a variable--its value is always "hello", so it's called a "string literal". Similarly for numbers:

    var num = 10;

    num is a variable because it's value can change, and 10 is a "numeric literal".


    2) theForm = document.getElementById("theForm");

    getElementById() returns one element--in this case the element with the id "theForm". But, then you do this:

    for (var i=0; i<theForm.length; i++)

    html elements do not have a .length property. arrays have a .length property. An html element is not an array. Try this:

    alert(theForm.length); //'undefined'

    However an html form element does have an .elements property, which is an array containing all the form elements, and it has a .length property.

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,862
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    var month_name = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    is the shortest way to define your month name array so that the names match the expected month numbers. Most javascript functionality counts months from zero instead of one so as to be able to drop the empty element from the definition of the array and make it even shorter.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


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
  •