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 7 of 7
  1. #1
    New to the CF scene
    Join Date
    Jan 2009
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    VERY simple function from a noob

    Hey guys, i'm just starting to learn javascript and know next to nothing about it.

    A friend of mine was helping me with validating a form and gave me the following script (which works like a charm) to make sure the user enters either a phone number or email address before submitting the form:

    Code:
    function checkPhoneEmail() {
    if ((document.getElementById('email').value=='' || document.getElementById('email').value==null) && (document.getElementById('phone').value=='' || document.getElementById('phone').value==null)) {
         alert("You must fill in a contact mehod: Phone or Email");
         return false;
      }
      else { return true; }
    }
    I also want to make sure the user provides a name on the form before submitting so i thought i might try to rework the code my friend did, but i can't get it going and really don't know where to start. I'm sure it's something simple, but being so new to all this, nothing seems simple haha.

    my code:
    Code:
    function checkName() {
    if (document.getElementById('name').value=='' || document.getElementById('name').value==null) {
    	alert("Please provide your name.");
    	return false;
    	}	
    	else {	return true; }
    }
    my Form:
    [HTML] <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" onsubmit="return checkPhoneEmail()">
    <label>Name: <input type="text" name="name" id="name" /></label><br />
    <label>Email: <input type="text" name="email" id="email" /></label><br />
    <label>Phone: <input type="text" name="phone" id="phone"></label><br>
    <input type="submit" name="submit" value="Go!!" onSubmit="return checkName()" />
    </form>[/HTML]

    Where'd did i go wrong?

    Thanks in advance for helping another newbie learn a bit!
    J

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,198
    Thanks
    80
    Thanked 4,453 Times in 4,418 Posts
    Well, you'll pardon me for saying so, but your friends code is sloppy and ineffective.

    (1) There's no need to check for null, because the ".value" property of any text field is always a string. It might be a blank string, but it will be a string.
    (2) With the code as written, a person could type in a single space and it would be accepted as valid.

    There are *tons* of validation scripts out on the web, 95% of which are much better than this.

    Anyway, if you are willing to stick with this validation (I hope you don't), all you need to do is change the onSubmit= in your submit button to onClick=. onsubmit is ONLY an event for the <form>, not for any of the form fields.

    If you want much better validation, ask again.

  • Users who have thanked Old Pedant for this post:

    MainStWebGuy (06-02-2009)

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,081
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    You should avoid giving names or id's to your variables/functions/arguments/forms words which are JavaScript methods/properties/attributes such as 'name' or 'id' or 'value' or 'text' or 'checked' or 'submit' or 'replace' or 'button' or 'radio' or 'parseInt'.


    Code:
    function checkName() {
    var x = document.getElementById('userName').value;
    x = x.replace(/^\s+|\s+$/g,"");   // strip leading and trailing spaces
    x = x.replace{/[^a-z\-\'\s]/gi, "");  // strip anything but a-z hyphen apostrophe space
    if (val.length < 2) {
    alert ("Please provide your name.");
    return false;
    else {
    return true; 
    }
    }
    Last edited by Philip M; 06-02-2009 at 09:27 PM.

  • Users who have thanked Philip M for this post:

    MainStWebGuy (06-02-2009)

  • #4
    New to the CF scene
    Join Date
    Jan 2009
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thank you both so much!

    I will not be sticking with this form of validation due to your insight! I thought about the fact that someone could just put in a space or something but wasn't sure how that would work.. thanks for clearing that up.

    I'm trying to get away from using the built in functions that DreamWeaver creates because other forum ppl tell me they suck...

    can you suggest a place to learn about validation/javascript?

    Just out of curiosity, what makes my buddies code sloppy? (no apology necessary, I'm just wondering what would be a better way to do it and what it would look like).

    Thanks again guys!

    Oh and thanks for the code snippet Phil!! I'll try to rework the checkPhoneEmail with your principles... VERY informative!
    Last edited by MainStWebGuy; 06-02-2009 at 09:31 PM. Reason: didn't see phil's post edits

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,081
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Code:
    <script type = "text/javascript">
    
    function checkPhoneEmail() {
    var e = document.getElementById('email').value;
    var p = document.getElementById('phone').value;
    if ((e.length < 5) && (p.length < 5) {
    alert("You must fill in a contact method: Phone or Email");
    return false;
    }
    else {
    if (e) {
    if (!(/^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@(([\w\-]?)+\.)+([a-z]{2,4})$/i.test(e))) {
    alert ("Invalid email address.  Please retry");
    return false;
    }
    }
    if (p) {
    if (/(^[0-9\s\-]{10,})$/gi.test(lstr.value)) { // telephone number, only digits, space, hyphen
     allowed. Minimum of 10 characters.
    alert ("Invalid phone number.  Please re-try");
    return false;
    }
    }
    return true; 
    }
    }
    </script>

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,198
    Thanks
    80
    Thanked 4,453 Times in 4,418 Posts
    Sloppy is checking for null when it's pointless.

    Sloppy is not checking for some *real* content, allowing just a single space.

    Philip's code is just one way to go, though whatever you do keep his email validation pretty much as is as a fine way to go.

    Myself, I prefer to dispense with id's for form fields. You *need* the name= in order for a form field to be sent on to the processing code (e.g., PHP), but the id is completely unneeded.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,198
    Thanks
    80
    Thanked 4,453 Times in 4,418 Posts
    Here's my example code, avoiding the use of ID's, as I said.
    Code:
    <html>
    <head>
    <script type="text/javascript">
    
    var reEM = /^[a-z0-9]([\w\.\-\+])+[a-z0-9]\@(([\w\-]?)+\.)+([a-z]{2,6})$/i;
    function validateEmail( fld )
    {
       if ( ! reEM.test( fld.value ) )
       {
           alert("Sorry, that doesn't look like a valid email address");
           fld.focus();
           return false;
       }
       return true;
    }
    function validatePhone( fld )
    {
        var ph = fld.value.replace(/[^\d]/g, "");
        // if 11 digits with leading 1, chop the 1
        if ( ph.length == 11 && ph.characterAt(0) == "1" ) ph = ph.substring(1);
        if ( ph.length != 10 )
        {
            alert("The phone number must contain 10 digits.");
            fld.focus();
            return false;
        }
        fld.value = "(" + ph.substring(0,3) + ") " + ph.substring(3,6) + "-" + ph.substring(6);
        return true;
    }
    
    function validateForm( form )
    {
        if ( form.uname.value.replace(/[^a-z]/ig,"").length < 3 )
        {
            alert("Your name should be at least 3 letters long.");
            form.uname.focus();
            return false;
        }
        return validateEmail(form.email) 
            && validatePhone(form.phone);
    }
    </script>
    </head>
    <body>
    
    <form method="POST" onsubmit="return validateForm(this);">
    <label>Name: <input type="text" name="uname" /></label><br />
    <label>Email: <input type="text" name="email" /></label><br />
    <label>Phone: <input type="text" name="phone" /></label><br>
    <input type="submit" name="submit" value="Go!!" />
    </form>
    
    </body>
    </html>


  •  

    Posting Permissions

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