Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8

Thread: form validation

  1. #1
    New Coder
    Join Date
    Feb 2008
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    form validation

    Hi all,

    I currently have a simple JS form validation script... in this instance, it checks to see if "Student" has a value, if it does, then "Grade" may not be left blank:

    Code:
    function formCheckGrade(formobj)
    	{
    		if ( formobj.elements['Student'].value != '' )
    		{
    				if ( formobj.elements['Grade'].value == '' )
    				{
    					alert('Error: student grade is missing');
    					return false;
    				}
    		}
    	return true;
    	}
    I'd like to create a new function so that 'Grade' CAN be left empty, but if a value is submitted, it will only allow the form to submit if the value of 'Grade' is an integer (0123456789):

    Code:
    function formCheckGrade(formobj) {  
    	if ( formobj.elements['Grade'].value != '' ) {  
            var strString = GetElementValue(objElement);
            var numeric = true;
            var chars = "0123456789";
            var len = strString.length;
            var char = "";
            for (i=0; i<len; i++) { 
                char = val.charAt(i); 
                if (chars.indexOf(char)==-1) { 
                    numeric = false; 
                } 
            }
            return numeric;
       }else {
    		alert('Error: grade must be an integer');
       		return false;
       }
    return true;
    }
    Currently, this gives me this error:

    'objElement' is undefined.

    Thanks.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,901
    Thanks
    79
    Thanked 4,423 Times in 4,388 Posts
    Well, first of all, checking to see if Student.value is '' would still allow somebody to enter just a single space character (even by accident). So should you do a better job of validating than that??

    And you say Grade should be an integer. And then you list just the values from 0 to 9. You mean a grade can't be higher than 9? Or do you mean you expect a number in the usual 0 to 100 range???

    GUESSING you want (a) a name of at least three non-space characters and (b) an integer grade from 0 to 100:
    Code:
    function formCheckGrade(formobj)
    {
        var student = formobj.Student.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim off spaces
        if ( student.length == 0 )
        {
            // if no name other than spaces...
            return true; // we accept the form
        }
        if ( student.length < 3 ) 
        {
            alert("Student name, if given, must be at least 3 characters");
            return false;
        }
        var grade = formobj.Grade.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim off spaces
        var gre = /^\d{1,3}$/
        if ( ! gre.test( grade ) || parseInt(grade,10) > 100 ) 
        {
            alert("Grade must be an integer from 0 to 100");
            return false;
        }
        // since we trimmed up the name and grade, put them back into the form:
        formobj.Student.value = student;
        formobj.Grade.value = grade;
        return true;
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    New Coder
    Join Date
    Feb 2008
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you!

    Sorry... in reality, in this new function, the value of "Student" doesn't matter.

    Code:
    function formCheckGrade(formobj)
    {
        var grade = formobj.Grade.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim off spaces
        var gre = /^\d{1,3}$/
        if ( ! gre.test( grade ) || parseInt(grade,10) > 100 ) 
        {
            alert("Grade must be an integer from 1 to 100");
            return false;
        }
        // since we trimmed up the name and grade, put them back into the form:
        formobj.Grade.value = grade;
        return true;
    }
    This works perfectly, except it throws an alert if the field "Grade" is left blank... it should allow if to be submitted.
    Last edited by wkilc; 11-13-2010 at 01:38 AM.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,901
    Thanks
    79
    Thanked 4,423 Times in 4,388 Posts
    Just add in a line similar to the one I had for Student:
    Code:
    function formCheckGrade(formobj)
    {
        var grade = formobj.Grade.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim off spaces
        if ( grade == "" ) return true; // okay to be blank
        var gre = /^\d{1,3}$/
        if ( ! gre.test( grade ) || parseInt(grade,10) > 100 ) 
        {
            alert("Grade must be an integer from 1 to 100");
            return false;
        }
        // since we trimmed up the name and grade, put them back into the form:
        formobj.Grade.value = grade;
        return true;
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New Coder
    Join Date
    Feb 2008
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Got it. Thanks again!

    Code:
    {
      if ( formobj.elements['Grade'].value != '' )
    {
        var grade = formobj.Grade.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim off spaces
        var gre = /^\d{1,3}$/
        if ( ! gre.test( grade ) || parseInt(grade,10) > 100 ) 
        {
            alert("Grade must be an integer from 1 to 100");
            return false;
        }
        // since we trimmed up the name and grade, put them back into the form:
        formobj.Grade.value = grade;
      }
        return true;
    }

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,901
    Thanks
    79
    Thanked 4,423 Times in 4,388 Posts
    Whoops! You changed something on me! That code will *NOT* prevent somebody from entering a 0 grade.

    If you really want to avoid 0, we have to fix it:
    Code:
    if ( ! gre.test( grade ) || parseInt(grade,10) > 100 || parseInt(grade,10) < 1)
    Or we could just do it all in the regular expression:[code]
    Code:
        var gre = /^([1-9]\d?|100)$/
        if ( ! gre.test( grade ) )
    If you are curious, that re is read thus:
    Code:
    /^([1-9]\d?|100)$/
    /.../ == designate a regular expression
    /^ == means look starting at the beginning of the text (nothing before the match)
    (...|...) == means a choice of 2 possiblities
    [1-9]  == a digit from 1 to 9
    \d? == any digit, but it is optional
    [1-9]\d? == 1,2,3,4,5,6,7,8,9,10 through 99 (see?  can't have a leading zero, 1 or 2 digits)
    100 == literally and exactly 100
    ([1-9]\d?|100) == 1,2,3,4,5,6,7,8,9,10 through 99, 100
    $/ == means must match the end of the text (nothing after the match allowed)
    /^([1-9]\d?|100)$/ == any integer from 1 to 100 with no leading or trailing junk
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    As a detail, it would be a good idea to strip not just leading/trailing spaces from the student name, but also anything except a-zA-Z hyphen apostrophe space(John Smith-O'Riley).

    Code:
    var student = student.replace(/[^a-z\-\'\s]/gi,"");
    This prevents the name being entered as ?????? or whatever.

  • #8
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    All these validations will be useless if you don't have validations on the server-side. Client-side validation is supposed to be just supplemental to the server-side validation. Server-side validation is a must.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________


  •  

    Posting Permissions

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