#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    Canada
    Posts
    185
    Rep Power
    0

    cgi error checking


    Code:
    #c_parser.py
    #import appropiate modules
    
    import cgi
    import cgitb; cgitb.enable()
    form = cgi.FieldStorage()
    print "Content-type: text/html"
    print
    
    
    
    #get form information
    
    try:
        """since pyhton executed at run time it makes sense to log errors as they occur"""
        
        name = form["name"].value
        if name.isalpha():
            name = name.lower()
        else:
            print "Please enter a valid name"
            print "<br/>"
            
        exp = form["Experience"].value
        level = form["Level"].value
        product = form["Product"].value
        
        area_code = form["area_code"].value
        if area_code.isalpha():
            print "Please enter a valid area code"
            print "<br/>"
            
        phone_prefix = form["p_prefix"].value
        if phone_prefix.isalpha():
            print "Please enter a valid phone prefix"
            print "<br/>"
            
        phone_suffix = form["p_suffix"].value
        if phone_suffix.isalpha():
            print "Please enter a valid phone suffix"
            print "<br/>"
            
        email = form["email"].value
        if "@" not in email:
            """possible to check if endswith .com or .net or .biz, maybe just make sure its ."""
            if email[:-4] != ".":
                print "please enter a valid email"
                print "<br/>"
        phone = area_code + "-" + phone_prefix + "-"+ phone_suffix
    except Exception, e:
        print "Please input your ", e
        """this only gives 1 error at a time since python is executed at run time"""
    else:
        pass
        #print name, exp, level, product, phone, email
    
    #===================================================print content and confirmation to the user
    So the following code will still let phone_prefix and phone_suffix go through if even one of the characters is a letter. How can i circumvent this and make sure ALL the characters for the phone number are numbers.

    also why does email[-4] not actually work.
    thank you alll for your response. I think i've been looking at this code way too long.

    I noticed in my pyhon book that isalpha and isdigit doesnt' check if ALL the string is alpha or isdigit. annoying.
    Last edited by caroundw5h; April 9th, 2004 at 05:11 PM.
    "In theory, there is no difference between theory and practice.
    But, in practice, there is."

  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    1) Your book is mistaken about isalpha and isdigit. From the docs:

    isalpha( )

    Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

    isdigit( )

    Return true if all characters in the string are digits and there is at least one character, false otherwise.
    However spaces are not alpha, so 'John Doe' would fail the isalpha test. Ditto for digits - '123 456' would fail isdigit, since it has a non-digit character.

    2) The reason that email[-4] doesn't work is because in the code it is written as email[:-4], which returns from the start of the string up to the -4th character, which will never equal '.'.

    However even if you correct the code this is still a bad test - it assumes that the final suffix is always 3 characters. My main email address ends in .co.uk - any address that ends with a country code will fail, as will .info, and probably lots of others that I can't think of at the moment.

    <rant>
    I get really irritated by websites that are overly restrictive about validating input such as email, phone numbers zip/post codes etc. They often assume that all their users are US residents - I have several times encountered web sites that insist I enter a US format telephone number, and have had to resort to entering a random string of numbers to get to the next screen. Even if a user is in the USA it is conceivable that they will want to enter a mobile phone number or additional information. In the unlikely event that someone from the site will phone me (and that I want them to), then I presume it will be a human doing the phoning. In that case why not let me enter whatever I like for the phone number - I have yet to see a validation routine that can parse a string like:

    "(+44) 20 8 123 4567 ext. #789 during UK office hours, (+44) 79123456 otherwise"

    This is perfectly understandable to a human, so long as they know that (+44) signifies an international number so they need to add the 00 prefix for that.

    In short, let the user enter whatever they damn well want.
    </rant>

    Dave - The Developers' Coach
    Last edited by DevCoach; April 9th, 2004 at 06:19 PM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    Canada
    Posts
    185
    Rep Power
    0
    LOL.

    Thank you so much Coach. Your going to become my new best friend around here. I was thinking along the same lines as you letting the user enter their info as long as it is not possible to be something malicious. you are right.

    I totally agree with you about those websites. Myself am from Canada and often times feel likethe U.S. think they are the only ppl on the web. They are like that, they like to come in overthrow and try to own it. HA HA. I like your rant though.


    so true @ u.s.
    "In theory, there is no difference between theory and practice.
    But, in practice, there is."

  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    Your welcome.

    I was going to add that for most sites, I consider "none of your business" to be a valid phone number.

    Email addresses are a different matter, since they are going to be used by a computer without any human intervention, so it is worthwhile checking that they are valid. However:

    1) checking for valid email addresses is complex, since there are a lot of valid variations on the basic format.

    2) even if you validate an address there is no guarantee that it is genuine - to do that you need to send an email to the address and ask the user to reply to it. Validation should only be used to protect the user from typos.

    3) it is more efficient to do the validation in the client rather than sending it to the server and back again. Here is a javascript email validation routine that I have used. I found it on the web ages ago, but do not have the original URL so cannot give the author the credit they deserve.
    Put this code somewhere in your web page:

    Code:
    <SCRIPT LANGUAGE="JavaScript">
    <!-- //Begin
    function emailCheck (emailStr) {
        var checkTLD=0;
        var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
        var emailPat=/^(.+)@(.+)$/;
        var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
        var validChars="\[^\\s" + specialChars + "\]";
        var quotedUser="(\"[^\"]*\")";
        var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
        var atom=validChars + '+';
        var word="(" + atom + "|" + quotedUser + ")";
        var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
        var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
        var matchArray=emailStr.match(emailPat);
        
        if (matchArray==null) {
            alert("The email address seems incorrect (check @ and .'s)");
            return false;
        }
        var user=matchArray[1];
        var domain=matchArray[2];
        
        for (i=0; i<user.length; i++) {
            if (user.charCodeAt(i)>127) {
                alert("The email address contains invalid characters.");
                return false;
           }
        }
        for (i=0; i<domain.length; i++) {
            if (domain.charCodeAt(i)>127) {
                alert("The email address contains invalid characters.");
                return false;
           }
        }
        if (user.match(userPat)==null) {
        alert("The email address doesn't seem to be valid.");
        return false;
        }
        var IPArray=domain.match(ipDomainPat);
        if (IPArray!=null) {
            for (var i=1;i<=4;i++) {
                if (IPArray[i]>255) {
                    alert("Destination IP address is invalid!");
                    return false;
                }
            }
            return true;
        }
         
        var atomPat=new RegExp("^" + atom + "$");
        var domArr=domain.split(".");
        var len=domArr.length;
        for (i=0;i<len;i++) {
            if (domArr[i].search(atomPat)==-1) {
                alert("The email address does not seem to be valid.");
                return false;
           }
        }
        
        if (checkTLD && domArr[domArr.length-1].length!=2 && 
        domArr[domArr.length-1].search(knownDomsPat)==-1) {
            alert("The address must end in a well-known domain or two letter " + "country.");
            return false;
        }
        
        if (len<2) {
            alert("The email address is missing a hostname!");
            return false;
        }
        
        // If we've gotten this far, everything's valid!
        return true;
    }
    
    //  End -->
    
    </script>
    To use it, call it in the onSubmit event of your form (assuming the form has a text box called 'email'):

    Code:
    <form name="form1" method="post" action="cgi/doStuff.py" onSubmit="return emailCheck(this.email.value)">
    If the validation fails it will immediately pop up a message box saying why, and not submit the form.

    Regards,

    Dave - The Developers' Coach

    Comments on this post

    • andywhitt agrees
    Last edited by DevCoach; April 10th, 2004 at 05:20 AM.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    Canada
    Posts
    185
    Rep Power
    0
    thanks coach, i will use it.
    "In theory, there is no difference between theory and practice.
    But, in practice, there is."


IMN logo majestic logo threadwatch logo seochat tools logo