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

    Angry New to javaScript and I am struggling help with JS Validation

    This is for an online course I am taking. I am not a coder but I am honestly trying to learn.


    Create a form that contains text inputs for the user's first name and last name.
    Add an email input for the user's email address.
    Add a select element that lists 5 school subjects and asks the user to choose their favorite subject.
    Make sure you have descriptive text before each input so that the user knows what they are supposed to enter or select for each input field.

    Next, use JavaScript to validate each form input and print an alert message to the user for each field that fails validation. Write a function that checks to make sure the user has not left any fields blank.

    Note: Do not use the "required" keyword on your HTML form inputs. Although this is one way of requiring user's to complete certain form inputs, you are specifcially being asked to use JavaScript to validate your form inputs instead.

    Here is my mess I made

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8" />
    <title>Assignment 6</title>
    <link rel="stylesheet" type="text/css" href="Assignment6.css">
    <script>
    <!--
    <script type="text/javascript">
        function checkForm()
        {
            var str = '';
            var elem = document.getElementById('myForm').elements;
            for(var i = 0; i < elem.length; i++)
            {
                
    	str += "<strong>Type: </strong>" + elem[i].type + "&nbsp;&nbsp;";
    	str += "<strong>Name: </strong>" + elem[i].name + "&nbsp;&nbsp;";
    	str += "<strong>Value: </strong><em>" + elem[i].value + "</em>&nbsp;&nbsp;";
    	str += "<br />";
    </script>
    <script>			
    	if(form.Email_Address.value.indexOf("@", 0) < 0) 
    {
        alert("This is not a valid e-mail address!");
            } 
            document.getElementById('lblValues').innerHTML = str;
        }			
    //-->
    </script>
    </head>
    
    <body>
    <h1>My name</h1>
    <hr/>
    
    <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
      Name: <input type="text" name="First_name" text= "First_name">
      <input type="submit" value="Submit">
    E-mail:<input type="text" name="email">
    <input type="submit" value="Submit">
      <br>
      <br>
      
    Select your favorite School Subject:<input list="School_Subject" name="School_Subject">
    <datalist id="School_Subject">
    <option value="Computer Science">
    <option value="Science">
    <option value="Math">
    <option value="P.E">
    <option value="Biology">
    </datalist>
    <br>
    
    <input type="submit" value="Submit Data" onclick="return checkForm(this.form);" />
    <input type="reset" value="Reset Form" >
    <p id="demo"></p>
    
    </form> 
    <hr />
    <div id="lblValues"></div>
    </body>
    </html>
    Last edited by vinyl-junkie; Jul 12th, 2019 at 05:17 AM. Reason: added code tags

  2. #2
    Master Coder sunfighter's Avatar
    Join Date
    Jan 2011
    Location
    West Des Moines, Iowa
    Posts
    8,120
    Thanks
    37
    Thanked 1,089 Times in 1,085 Posts
    Maybe be a little above your pay grade and not as good as it should be, after all browsers do this for you now and didn't need to do this in a number of years. But here is my take on it:

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>My bad</title>
      <!-- <link rel="stylesheet" href="style.css"> -->
    </head>
    
    <body>
    <form id='myForm' onsubmit="return validateForm();" action="https://www.google.com/webhp?client=firefox-b-1-d">
      <label for="fname">First Name : <br><input id="fname" placeholder='First Name'></label><div id=fnameErrorMessage style="color: red;margin-left: 10px;"></div><br><br>
      <label for="lname">Last Name : <br><input id="lname" placeholder='Last Name'></label><div id=lnameErrorMessage style="color: red;margin-left: 10px;"></div><br><br>
      <label for="email">Email : <br><input id="email" placeholder='email address'></label><div id=emailErrorMessage style="color: red;margin-left: 10px;"></div><br>
      <br>Pick Your Favorite Subject :<div id="group" style="color: red;margin-left: 10px;"></div><br>
      <hr style="color:red;float:left;width:180px;"><br><br>
      <input type="radio" name='subject' value="Math">Math<br>
      <input type="radio" name='subject' value="History">History<br>
      <input type="radio" name='subject' value="Geography">Geography<br>
      <input type="radio" name='subject' value="Spelling">Spelling<br>
      <input type="radio" name='subject' value="Lunch">Lunch<br>
      <input type="submit" value="Submit">
    </form>
    
    <script>
    function validateForm(){
      /* clear any error messages for a submit or re-submit */
      document.getElementById('group').innerHTML = '';
      document.getElementById('fnameErrorMessage').innerHTML = '';
      document.getElementById('lnameErrorMessage').innerHTML = '';
      document.getElementById('emailErrorMessage').innerHTML = '';
    
      /* declare variables */
      var elem = document.getElementById('myForm').elements;
      var group = document.getElementsByName('subject');
      var err = '';
    
      /* Check the radio buttons */
      for (var i=0; i<group.length; i++) {
        if (group[i].checked){
          break;
        } 
      }
      if (i == group.length){
        document.getElementById('group').innerHTML = "No radio button is checked";
        err++;
      }
      
      /* Check for blank inputs */
      for(var i = 0; i < elem.length; i++){
        if(elem[i].value === ''){
          document.getElementById(elem[i].id + 'ErrorMessage').innerHTML = 'This must be filled out';
          err++;
        };
      }
    
      /* Email should be done with regex not like this */
      var firstEmail = elem[2].value.includes("@"); // should be at top with all declared statements
      if(firstEmail !== true){
        document.getElementById(elem[2].id + 'ErrorMessage').innerHTML = 'Email Address is incorrect';
        err++;
      }
    
      if(err === '') return true;
      return false;
    }
    </script>
    </body>
    </html>
    Last edited by sunfighter; Jul 12th, 2019 at 11:09 PM.
    Evolution - The non-random survival of random variants.
    Physics is actually atoms trying to understand themselves.

  3. Users who have thanked sunfighter for this post:

    mcgraw927 (Jul 13th, 2019)

  4. #3
    Senior Coder coothead's Avatar
    Join Date
    Jan 2004
    Location
    chertsey, a small town 25 miles south west of london, england.
    Posts
    3,525
    Thanks
    3
    Thanked 630 Times in 616 Posts
    Hi there mcgraw927,

    my take on your problem, also allows HTML validation for those who
    might prefer to have JavaScript disabled whilst submitting forms.

    Code:
    
    <!DOCTYPE HTML>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
    
    <title>Assignment 6</title>
    
    <!--<link rel="stylesheet" href="Assignment6.css" media="screen">-->
    
    <style media="screen">
    body {
        background-color: #f9f9f9;
        font: normal 1em / 1.5em BlinkMacSystemFont, -apple-system, 'Segoe UI', roboto, helvetica, arial, sans-serif;
     }
    
    h1 {
        font-size: 1.25em;
        color: #555;
        text-align: center;
        text-transform: uppercase;
        letter-spacing: 1px;
     }
    
    #myForm {
        display: inline-block;
        padding: 1em;
        border: 1px solid #999;
        border-radius: 0.75em;
        background-color: #fff;
        box-shadow: inset 0 0 1em rgba( 0, 0, 0, 0.4 ), 
             0.25em 0.25em 0.25em rgba( 0, 0, 0, 0.4 );
     }
    
    #myForm fieldset {
        padding: 1em;
        margin: 0.75em;
        border: 1px solid #aaf;
        border-radius: 0.75em;
        background-color: rgba( 239, 239, 255, 0.75 );
     }
    #myForm fieldset:last-of-type {
        text-align: center;
     }
    
    #myForm span {
        display: block;
        min-height: 1.5em;
        margin: 0.5em 0;
        color: #900;
     }
    </style>
    
    </head>
    <body>
    
    <form id="myForm" action="#">
    
     <h1>My name</h1>
    
     <fieldset>
    
      <label for="name">Name: </label>
      <input type="text" id="name" name="First_name" placeholder="Example - John Smith" required>
      <span id="info1"></span>
    
      <label for="email">E-mail: </label>
      <input type="email" id="email" name="email"  placeholder="[email protected]" required>
      <span id="info2"></span>
    
     <label for="subject">Select your favorite School Subject:</label>
      <select id="subject" name="subject" required>
       <option value=''>options</option>
       <option value="Computer Science">Computer Science</option>
       <option value="Science">Science</option>
       <option value="Maths">Maths</option>
       <option value="P.E">P.E.</option>
       <option value="Biology">Biology</option>
      </select>
    
      <span id="info3"></span>
    
     </fieldset>
    
     <fieldset>
    
      <input type="submit" id="sub" value="Submit Data" >
      <input type="reset" id="res" value="Reset Form">
    
     </fieldset>
    
    </form> 
    
    <script>
    (function( d ) {
       'use strict';
       var frm, elem1, elem2, elem3, 
           info1, info2, info3, count = 3 ; 
    
    /************* reset form on page load *************/
    
           frm = d.getElementById( 'myForm' );
           frm.reset();
    
    /***************************************************/
    
           info1 = d.getElementById( 'info1' );
           info2 = d.getElementById( 'info2' );
           info3 = d.getElementById( 'info3' );
    
    /* if javascript is disabled, then we have HTML validation */
    
           elem1 = d.getElementById( 'name' );
           elem1.removeAttribute( 'required' );
           elem2 = d.getElementById( 'email' );
           elem2.removeAttribute( 'required' );
           elem3 = d.getElementById( 'subject' );
           elem3.removeAttribute( 'required' );
    
    /***********************************************************/
    
    /************ validate inputs a select elements ************/
    
       frm.addEventListener( 'submit',  
          function(e) {
             e.preventDefault();
      
             if ( elem1.value === '' ) {
                  info1.textContent = 'This is not a valid name!';
                }
             else { 
                  if ( info1.textContent != '' ) {
                       info1.textContent = '';
                       count --;
                   }
                  }
    
             if ( elem2.value === '' ) {
                  info2.textContent =  'This is not a valid e-mail address!';
                } 
             else {
                  if ( info2.textContent != '' ) {
                       info2.textContent = '';
                       count --;
                   }
                  }
    
             if ( elem3.value === '' ) {
                  info3.textContent =  'This is not a valid subject!';
                }
             else {
                  if ( info3.textContent != '' ) {
                       info3.textContent = '';
                       count --;
                   }
                  }
       
             if ( count === 0 ) {
                  frm.submit();
             }
    	}, false );	
    
    /***********************************************************/
    
    /***************** reset the span elements *****************/
    
       document.getElementById( 'res' ).addEventListener( 'click',  
          function() {	
                  info1.textContent = '';
                  info2.textContent = '';
                  info3.textContent = '';
                  count = 3;
             }, false );
    
    /***********************************************************/
    
    }( document ));
    </script>
    
    </body>
    </html>

    coothead
    ~ the original bald headed old fart ~

  5. Users who have thanked coothead for this post:

    mcgraw927 (Jul 13th, 2019)

  6. #4
    New to the CF scene
    Join Date
    Jun 2019
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts
    sunfighter- Thanks for taking the time,that was exactly what I needed. I have a couple more weeks in this class then I will be done. A couple weeks ago I had a similar issue, I was able to complete the assignment but the post I received were basically saying you are learning the old way or this method inst the standard anymore. Which kind of frustrates me a little because I am paying to learn JS but I think the main premise is though what I am being taught is outdated, it is basic JS so I can learn a base before moving in to the latest's and greatest. Well that is what I am telling myself.

  7. #5
    New to the CF scene
    Join Date
    Jun 2019
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts
    coothead- I like the form, but my instructor would know it wasn't from me. Thanks for taking the time !


 

Tags for this Thread

Posting Permissions

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