0

JS newbie here. I'm making a form with validation that creates a p tag when submitted and validated. I just cant seem to get it to work, because the site reloads when no errors are displayed, instead of creating the paragraph with the inputs. Seems like I've tried every suggested solution there is, but nothing works for me. I hope someone out there might know what the issue is!

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Form validation</title>
<link rel="stylesheet" href="stylesheet.css">
<script src="script.js"></script> 
</head>
<body>
  <form name="contactForm" onsubmit="return validateForm()">
      <h2>Application Form</h2>
      <div class="row">
          <label>Förnamn</label>
          <input type="text" name="fname">
          <div class="error" id="fnameErr"></div>
      </div>
      <div class="row">
        <label>Efternamn</label>
        <input type="text" name="lname">
        <div class="error" id="lnameErr"></div>
    </div>
      <div class="row">
          <label>Email Address</label>
          <input type="text" name="email">
          <div class="error" id="emailErr"></div>
      </div>
      <div class="row">
          <input type="submit" value="Submit">
      </div>
  </form>
  <div class="wrapper">
    <div id="list">

    </div>
  </div>
</body>
</html>

JS:

// Defining a function to display error message
function printError(elemId, hintMsg) {
    document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form 
function validateForm() {
    // Retrieving the values of form elements 
    var fname = document.contactForm.fname.value;
    var lname = document.contactForm.lname.value;
    var email = document.contactForm.email.value;
    
    // Defining error variables with a default value
    var fnameErr = lnameErr = emailErr = true;
    
    // Validate name
    if(fname == "") {
        printError("fnameErr", "Please enter your name");
    } else {
        var regex = /^[a-zA-Z\s]+$/;                
        if(regex.test(fname) === false) {
            printError("fnameErr", "Please enter a valid name");
        } else {
            printError("fnameErr", "");
            fnameErr = false;
        }
    }

    if(lname == "") {
        printError("lnameErr", "Please enter your name");
    } else {
        var regex = /^[a-zA-Z\s]+$/;                
        if(regex.test(lname) === false) {
            printError("lnameErr", "Please enter a valid name");
        } else {
            printError("lnameErr", "");
            lnameErr = false;
        }
    }
    
    // Validate email address
    if(email == "") {
        printError("emailErr", "Please enter your email address");
    } else {
        // Regular expression for basic email validation
        var regex = /^\S+@\S+\.\S+$/;
        if(regex.test(email) === false) {
            printError("emailErr", "Please enter a valid email address");
        } else{
            printError("emailErr", "");
            emailErr = false;
        }
    }
    
    // Prevent the form from being submitted if there are any errors
    if((fnameErr || lnameErr || emailErr) == true) {
       return false;
    } else {
            document.getElementById("add").onclick  = function() {
                var p = document.createElement("p");
                var fname = document.getElementsByName("fname").value; 
                var lname = document.getElementsByName("lname").value;
                var email = document.getElementsByName("email").value;
                p.innerHTML = fname + "<br />" + lname + "<br />" + email;
                document.getElementById("list").appendChild(p);
        };
    }
};
  • Hello, you need to `preventDefault()` action for the form : https://stackoverflow.com/questions/17709140/how-to-prevent-default-on-form-submit. Otherwise the default action of the form will be to get submitted, as per action attribute value, if given, or 'nowhere' if not – St3an Apr 26 '21 at 13:26
  • @St3an That worked, but it still doesn't create the p element, any idea what might be wrong? – Oscar Hedlund Apr 26 '21 at 13:32
  • 1
    `document.getElementById("add").onclick = function() { ...` I can't see any element with the "add' id in your form... – St3an Apr 26 '21 at 13:35
  • @St3an my bad, the input submit is supposed to have the class add, tested it and it adds a paragraph, but the values are undefined. – Oscar Hedlund Apr 26 '21 at 13:37
  • Can you edit your answer and correct html subsequently please (...`add` ...)... ? Given the present code I don't see any problem with `document.getElementsByName("...").value;` parts... – St3an Apr 26 '21 at 13:45

1 Answers1

1

You can prevent a erroneous form from submitting with checkValidity() like this...

<button type="submit" formaction="if(this.form.checkValidity()){this.form.submit();} else {alert('Not valid!');}">Submit</button>

Replace my alert() with whatever you had in mind.

SomeUser
  • 11
  • 1