Validating name field with Javascript

Hi,

I have a contact form. And I’m just experimenting with validating the name field. I have a message there in green. And the CSS has a class so that if there’s an error, the message in green changes to red. But that is not working. I don’t know why. Here’s the code:


<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Contact Form</title>
    <link href="contactform.css" rel="stylesheet">
    <script src="contactform.js"></script>
</head>
<body>
    <h1>Contact Form</h1>
    <!-- Turn HTML5 validation off to test Javascript data validation -->
    <form id="contactform" action="#" method="post" novalidate>
        <p><i>Please complete the form. Mandatory fields are marked with a </i><em>*</em></p>
        <!-- Patient's name -->
        <fieldset>
            <legend>Patient's Name</legend>
            <label for="name">First Name <em>*</em></label>
                <input id="name" required>
                <p><span id = "fieldmessage" class="infomessage">Your name should be at least two alpha characters</span></p>
            <label for="surname">Last Name <em>*</em></label>
                <input id="surname" required>
                <p><span id = "errorMessage"></span></p>
            <label for="title">Title <em>*</em></label>
                <select id="title"  required>
                <option value="">Please select</option>
                <option value="mr">Mr.</option>
                <option value="ms">Ms.</option>
                <option value="mrs">Mrs.</option>
                <option value="miss">Miss.</option>
                <option value="master">Master.</option>
                </select><br>
                <p><span id = "errorMessage"></span></p>
        </fieldset>
        <!-- Contact details -->
        <fieldset>
            <legend>Contact Details</legend>
            <label for="telephone">Telephone</label>
                <input id="telephone">
                <p><span id = "errorMessage"></span></p>
            <label for="email">Email <em>*</em></label>
                <input id="email" type="email" required>
                <p><span id = "errorMessage"></span></p>
        </fieldset>
        <!-- Health Number -->
        <fieldset>
            <legend>Health Information</legend>
            <label for="health-number">Health Authority Number <em>*</em></label>
                <input id="health-number" type="alphanumeric" min="0" max="120" step="0.1" required>
                <p><span id = "errorMessage"></span></p>
        </fieldset>
        <p><input type="submit" value="Submit" id=submit></p>
        <div id="display-message"></div>
    </form>
</body>




body {
  font-family: 'Palatino Linotype', serif;
  max-width: 600px;
  padding: 10px 30px;
}

h1 {
  margin-bottom: 0px;
}

p {
  margin-top: 0px;
}

fieldset {
  margin-bottom: 20px;
  padding: 10px;
}

legend {
  padding: 0px 3px;
  font-weight: bold;
  font-variant: small-caps;
}

label {
  width: 110px;
  display: inline-block;
  vertical-align: top;
  margin: 6px;
}

em {
  font-weight: bold;
  font-style: normal;
  color: #f00;
}

input:focus {
  background: #eaeaea;
}

input, textarea {
  width: 249px;
}

textarea {
  height: 100px;
}

select {
  width: 254px;
}

input[type=checkbox] {
  width: 10px;
}

input[type=submit] {
  width: 150px;
  padding: 10px;
}

input:required:invalid {
  background-color: white;
}

.infomessage{
  color: green;
}

.infoerror{
  color: red;
}



function main(){
    document.getElementById("contactform").onsubmit = validateAll;
    document.getElementById("name").onblur = validateField;
}

function message(){
    alert(this.value);
}

function validateField(){
    var noErrors = true;
    if(this.value.length<2){
        noErrors=false;
        alert ("You need to input more than 1 character in "+ this.id);
    }
    if(noErrors==false){
        var temp = document.getElementById(this.id + "fieldmessage");
        temp.className = "infoerror";
    }
}

function validateAll(){
    return false;
}

window.onload = main;




By the way, the demo is here: http://jsfiddle.net/Assembly21/D5xw2/ or here: http://codepen.io/CarolinaSawney/pen/AyoIa - as the first one does an error on submit.

Thanks in advance.

Hi (again),

On the fiddle you posted:

Remove this from the top of the markup window:

    <title>Contact Form</title>
    <link href="contactform.css" rel="stylesheet">
    <script src="contactform.js"></script>  
</head>
<body>

and this from the bottom:

</body>
</html>

Your JS has a typo:

document.getElementById("contactform").onsubmit = ValidateAll;

should be:

document.getElementById("contactform").onsubmit = [B][COLOR="#FF0000"]v[/COLOR][/B]alidateAll;

Change that and your code will work as desired.

Demo

Also, in this function:

function validateField() {
    var noErrors = true;
    if (this.value.length < 2) {
        noErrors = false;
        alert("You need to input more than 1 character in " + this.id);
    }
    if (noErrors == false) {
        var temp = document.getElementById(this.id + "fieldmessage");
        temp.className = "infoerror";
    }
}

Your temp variable is equal to “namefieldmessage” and there is no element on the page with this id.

You’ll need to do something like:

function validateField() {
    var noErrors = true;
    if (this.value.length < 2) {
        noErrors = false;
        alert("You need to input more than 1 character in " + this.id);
    }
    if (noErrors === false) {
        [B][COLOR="#FF0000"]this.className = "infoerror";[/COLOR][/B]
    }
}

instead.

Thanks a lot, it worked.

Now: the onblur event associated to validate field, doesn’t check it when you finish typing, it does it onsubmit. Why is that? Is it that when I submit, the programme goes to validate all and then one goes to validate field onblur? So it’s not really an onblur…

Fiddle does an error if you submit the HTML form there, but it works on codepen. Is that the way it is?

Thanks again!

No probs :slight_smile:

onblur fires when you click out of the field, not when you finish typing.
For that you would have to use something like keypress/keyup/keydown

The fiddle will throw an error as you are trying to submit to a non-existent address.
Codepen seems to not even try submitting the form.