www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 26

Thread: Javascript validation help

Hybrid View

  1. #1
    Join Date
    May 2012
    Posts
    12

    Javascript validation help

    Hello there, although being new to the forum I intend to start using it quite a lot after seeing how busy and active it is!

    I will be as thorough as I can in my explanation below, if anything is unclear then please let me know!

    OK, basically I am creating a form with the fields to input - first-name, surname, phone number and email. I have a simple form wrote up, completely unstyled and plain which you shall see below. What I need to do is for the phone number and email address fields, is to validate whether the correct string is in the fields (numbers/amount of numbers for phone number and whether the email address is valid)

    Now of course I have looked over the internet and found numerous tutorials and code examples for validation but trying to pick and choose and then incorporate others code with your own is hard; and I couldn't find anything that helps me exactly. (you will see below that I have a small form of simple validation, but it is not what I want)). What you will see in my code below is that I have a single function that is called with the submit button that checks to see if the telephone has only numbers in the field. This works however it has lead me onto my next point.

    When I click the submit button, I want both the email and phone number checked for validation; but rather than having a pop-up alert message, I would like the errors displayed below the field that they correspond with. So, to put it simply, could someone help/show me to how to write the correct function/functions to check both the fields (on the click of submit) and if one/either are wrong, then an error message is displayed below the field.

    Just to mention, I am a total novice to JavaScript, and most of my code and has been referenced from tutorials and stuff.

    Code to follow:

    HTML Form.

    Code:
    <form  name="clientValidate" id="custInfo" autocomplete="on";">
       <fieldset>
          <legend>Required Customer Information</legend>
          
             <label>First Name:
                <input id="firstName" name="name" type="text"
                         placeholder="Forename" autofocus>
             </label>
             
             <label>Surname:
                <input id="Surname" name="sName" type="text"
                         placeholder="Surname">
             </label>
             
             <label>Telephone:
                <input id="tel" name="telephoneNum" type="tel" 
                         placeholder="07123456789">
             </label>
             
             <label>Email Address:
                <input id="emailer" name="email" type="email"
                         placeholder="E.G email@email.com">
             </label>
          
       </fieldset>
       <input type="button" onclick="isNumeric(document.getElementById('tel'), 'Numbers Only Please')" value="Submit!"/>   
    </form>
    Current JS

    Code:
    function isNumeric(elem, helperMsg){
       var numericExpression = /^[0-9]+$/;
       if(elem.value.match(numericExpression)){
          return true;
       }else{
          alert(helperMsg);
          elem.focus();
          return false;
       }
    }
    Thanks in advance, and I will keep a check on the thread

  2. #2
    Join Date
    Apr 2011
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    33
    Well, first, I'd encourage you to keep working.

    To show messages on the page, a general approach is to manipulate the DOM directly. For example, you might have an empty HTML element (div or p) with an id of "phonenumerror" or similar. In the css, this element is set "display:none;", or the color matches the background, or something similar.

    Your Javascript then, when it discovered the error condition, would set the CSS properties of the DOM object to visible. If the DOM object is empty, it can also write the error text to the InnerHTML of that object.

    Does this help a bit?

  3. #3
    Join Date
    May 2012
    Posts
    12
    Thanks for the reply.
    I am following the logic I think. However, I have no real knowledge in actually writing javascript; that's where my main problem lies.

    So under telephone number, I have placed

    Code:
    <label>Telephone:
    		<input id="tel" name="telephoneNum" type="tel" 
    			placeholder="07123456789">
    		<p id="phoneNumError">Please Enter Numbers Only!</p>
    			
            </label>
    And then in CSS, set the property to display:none to hide it. And I have done the same for the email.

    And now I reach my roadblock, I dont know how to write the function/functions to get these working.

    As fair as my logic goes, I'm guessing that I need a function that reads the submit button being pressed which then sets of two more functions inside that one?

    So

    functionforsubmitbeingpressed{

    functiontocheckphone{

    }
    functiontocheckemail{

    }

    }

    Right kind of lines?

    BUT as I said, I don't know how to write these functions, if that's even correct.

  4. #4
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,674
    try this

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>...</title>
    <head>
    <style type="text/css">
    body{text-align:center;font-family:Verdana,Arial;font-size:13px;background-color:#fff;color:#000;padding-top:200px;}
    legend{font-size:14px;font-weight:bold;}
    input{text-align:center;}
    input[type="button"]{margin-top:15px;}
    div.err{display:block;position:absolute;z-index:500;color:Crimson;background-color:#fff;border:1px solid Crimson;padding:10px;font-weight:bold;}
    </style>
    </head>
    <body>
    <center>
    <form name="custInfo" id="custInfo" autocomplete="on">
    <fieldset>
    <legend>Required Customer Information</legend>
    <label>First Name:<input id="firstName" name="name" type="text" placeholder="Forename" autofocus></label>
    <label>Surname:<input id="Surname" name="sName" type="text" placeholder="Surname"></label>
    <label>Telephone:<input id="tel" name="telephoneNum" type="tel" placeholder="07123456789"></label>
    <label>Email Address:<input id="emailer" name="email" type="email" placeholder="email@email.com"></label>
    <br />
    <input type="button" value="Submit!" onclick="isValid()" />
    </fieldset>
    </form>
    </center>
    <script type="text/javascript">
    /* 2 reg exp's for digits and for non-digits */
    var digs_only=/^[\d]{1,}$/g,
    non_digs=/[^\d]{1,}/g,
    /* reg exp for checking email-format */
    mail_path=/^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i,
    /* shorthand for the form */
    frm=document.forms['custInfo'],
    /* error messages array (index starts at 0) */
    err_msg=['This field can not be empty!','Incorrect email format!'],
    /* 48x48 px image for error messages*/
    err_msg_img='http://www.smc.eu/portal/WebContent/basket_v2/resources/warning_new.png';
    
    
    /* this function removes 'non-digits' from the element's value */
    function digitsOnly(obj){var val=obj.value;if(val.length>0){if(!digs_only.test(val)){obj.value=val.replace(non_digs,'');obj.focus();}}}
    /* this function gets position data for any element 
    save it for future use it is very useful */ 
    function gPD(element){var left=element.offsetLeft,top=element.offsetTop;for(var parent=element.offsetParent;parent;parent=parent.offsetParent){left+=parent.offsetLeft;top+=parent.offsetTop;}return{left:left,top:top,width:element.offsetWidth,height:element.offsetHeight};}
    /* this function removes the Error Message div */
    function remErr(){document.body.removeChild(document.getElementById('errdiv'));}
    /* this function shows the Error Message div */
    function showErr(x,y,msg){
    try{remErr();}catch(e){}
    var div=document.createElement('div');
    div.style.left=(x+10)+'px';
    div.style.top=(y-40)+'px';
    div.setAttribute('class','err');
    div.setAttribute('id','errdiv');
    div.innerHTML='<img alt="Error" src='+err_msg_img+' style="position:absolute;top:-30px;left:-20px;" onload="setTimeout(\'remErr()\',2000);" />';
    div.innerHTML+=err_msg[msg];
    try{div.style.borderRadius='5px';}catch(e){}
    document.body.appendChild(div);
    /* if no error image used uncomment this line */
    //setTimeout('remErr()',2000);
    }
    /* the telephone field test on keyup and onblur */
    frm.telephoneNum.onkeyup=function(){digitsOnly(this);};
    frm.telephoneNum.onblur=function(){digitsOnly(this);};
    
    function isValid(){
    var valid=true;
    /* because of there were no any conditions for Name & Surname fields given, we'll check these fields only on 'empty' */
    if(frm.name.value.length<1){valid=false;showErr(gPD(frm.name.parentNode)['left'],gPD(frm.name)['top'],0);frm.name.focus();return;}
    if(frm.sName.value.length<1){valid=false;showErr(gPD(frm.sName.parentNode)['left'],gPD(frm.sName)['top'],0);frm.sName.focus();return;}
    if(frm.telephoneNum.value.length<1){valid=false;showErr(gPD(frm.telephoneNum.parentNode)['left'],gPD(frm.telephoneNum)['top'],0);frm.telephoneNum.focus();return;}
    if(!mail_path.test(frm.email.value)){valid=false;showErr(gPD(frm.email.parentNode)['left'],gPD(frm.email)['top'],1);frm.email.focus();return;}
    if(valid){frm.submit();}
    }
    </script>
    </body>
    </html>

  5. #5
    Join Date
    May 2012
    Posts
    12
    Well that is brilliant, where did you quote it from?

    I am going to split it all up into separate sheets and change the names and everything; then go on and read through all the javascript and try to understand it. If I find any specific problems I do not understand, I will post back!

  6. #6
    Join Date
    Feb 2011
    Posts
    83
    Padonak's code is absolutely brilliant.

    Can you go further to change the telephone number to format 123-555-2345 x 7890? When you type the first three area code, it automatically moves to the first 5 so you can type another three then region code, then moves to 2 so you can type last four then moves to 7, so you can type none, or 1, 2, or 3 or 4 digits. Is this possible?

    Thanks for your brilliant code, Padonak

  7. #7
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,674
    i do not quote it from somewhere. excepting the function that gets position data, error image (which i found with google) and the regExp for email, i wrote it 10 mins ago lol

  8. #8
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,674
    hey there's no need to split it up or change names )) maybe just the image but as for me i wouldn't - who cares? ))

  9. #9
    Join Date
    May 2012
    Posts
    12
    Quote Originally Posted by Padonak View Post
    i do not quote it from somewhere. excepting the function that gets position data, error image (which i found with google) and the regExp for email, i wrote it 10 mins ago lol
    aye I apologise, just before I came onto this topic I was reading another with someone who had code "quoted from blahblah" and then I came on here and typed that haha


    Quote Originally Posted by Padonak View Post
    hey there's no need to split it up or change names )) maybe just the image but as for me i wouldn't - who cares? ))
    Only because I like to have the HTML/CSS/JS in separate files in order for it to not get too clumpy

  10. #10
    Join Date
    May 2012
    Posts
    12
    The problem I am having at the moment is that when I try to split the 3 lots of code up into different pages, it not longer works. I have done the normal checks e.g Make sure all pages are linked, opening/closing curly brackets etc but cant seem to see why?

    Anything that I'm missing?

    Will keep trying to find out why anyhow

  11. #11
    Join Date
    Apr 2011
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    33
    Any JS must all be available to the loaded page in order for it to run in a browser.

    So, all code snippets must be in the page's source HTML itself, or, you can do it this way:
    Code:
    <script type='text/javascript' src='http://mysite.com/js/somescript.js'></script>
    Note that the closing SCRIPT tag is not optional when doing this, and, also, that you must remove any SCRIPT tags from JS files that are sourced in this manner.

    HTH,

  12. #12
    Join Date
    Apr 2011
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    33
    I'll also add that Firefox's Firebug, Opera's Dragonfly, or Google Chrome's debugger (w/e it is called) are a MUST when debugging JS. MS IE's F12 tools ... let's just say I usually develop JS in a different browser and only test IE after it's finished

  13. #13
    Join Date
    May 2012
    Posts
    12
    Quote Originally Posted by dalecosp View Post
    Any JS must all be available to the loaded page in order for it to run in a browser.

    So, all code snippets must be in the page's source HTML itself, or, you can do it this way:
    Code:
    <script type='text/javascript' src='http://mysite.com/js/somescript.js'></script>
    Note that the closing SCRIPT tag is not optional when doing this, and, also, that you must remove any SCRIPT tags from JS files that are sourced in this manner.

    HTH,
    Ok, originally I was using this line - <script src="javascript.js" type="text/javascript"></script> in the head of my html. I thought this was acceptable and all I would require?


    Also, I am jsut running the page from harddrive to chrome.
    Quote Originally Posted by dalecosp View Post
    I'll also add that Firefox's Firebug, Opera's Dragonfly, or Google Chrome's debugger (w/e it is called) are a MUST when debugging JS. MS IE's F12 tools ... let's just say I usually develop JS in a different browser and only test IE after it's finished
    And thankyou for the reccomendation

  14. #14
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,674
    i tested the page in Opera, Safari, Chrome, IE and FF before posting the code ))

    @rs353: note, the script (internal or external) must go below the form!

  15. #15
    Join Date
    May 2012
    Posts
    12
    Quote Originally Posted by Padonak View Post
    i tested the page in Opera, Safari, Chrome, IE and FF before posting the code ))

    @rs353: note, the script (internal or external) must go below the form!
    Would it not in essence be below the code by default if it was external?

    Is it not as simple as simply putting the javascript onto separate page?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles