Data validation: telephone field not empty

Hello,

Here’s my (slightly updated) code for this contact form.

I’m experimenting to gradually include more checks.

Here I added the function validatePhoneField and the first test functionFieldEmpty. But it seems it’s not working.

Here’s a demo: http://codepen.io/CarolinaSawney/pen/rJkFH.

And for the record I also copy it here:


<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="forename">First Name <em>*</em></label>
                <input id="forename" required>
                <span id = "forenamefieldmessage" class="infomessage">Your name should be at least two letters</span>
            <label for="surname">Last Name <em>*</em></label>
                <input id="surname" required>
                <p><span id = "surnamefieldmessage" class="infomessage"></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 = "titlefieldmessage" class="infomessage"></span></p>
        </fieldset>
        <!-- Contact details -->
        <fieldset>
            <legend>Contact Details</legend>  
            <label for="telephone">Telephone</label>
                <input id="telephone">
                <span id = "telephonefieldmessage" class="infomessage">Write only numbers with no spaces or dashes</span>
            <label for="email">Email <em>*</em></label>
                <input id="email" type="email" required>
                <span id = "emailinfomessage" class="infomessage"></span>
        </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>



Here’s the JS:


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

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

function validatePhoneField(){
	var test1 = fieldEmpty(this); 
	var result = test1; 
	return result; 
} 

function fieldEmpty(){
	var valid = true; 
 	if(id.value==""){
		valid = false; 
     alert("Blank")
  } 
}

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;



Also, I’m not sure about the second function message, it seems it’s not really doing anything.

Thanks a lot!

Creating a function for each input?

I do not wish to sound condescending, but that seems like a lot of coding for one purpose.

If I may offer some unsolicited advice (as opposed to what you are soliciting).

Keeping the form, itself, as it is, you can simplify your custom validation. Create one function for trimming whitespace (so no one can enter a few spaces to bypass checking for blank value), then create one function for the actual validation. Also, instead of a submit button, use a type=“button” and give it an onclick=“return checkData(this.form);” attribute, using JavaScript to submit the form (thereby thwarting people who disable javascript to bypass validation.)


<script type="text/javascript">
   function trimStr(str){ return str.replace(/^\\s+|\\s+$/gi,''); }// Removes spaces/tabs from beginning and end of string.

   function checkData(formObj){
      var warn = "";//warn will contain concatenated alerts so you can put them all into one alert instead of several.
      formObj.forename.value = trimStr(formObj.forename.value);
      formObj.surname.value = trimStr(formObj.surname.value);
      formObj.telephone.value = trimStr(formObj.telephone.value);
      formObj.health-number.value = trimStr(formObj.health-number.value);

      if(formObj.forename.value === "") { warn += "Please enter a First Name.\
"; }
      if(formObj.surname.value === "") { warn += "Please enter a Last Name.\
"; }
      if(formObj.title.selectedIndex === 0) { warn += "Please select a Title.\
"; }
      if(formObj.telephone.value === "") { warn += "Please enter a Telephone Number.\
"; }
      if(formObj.health-number.value === "") { warn += "Please enter a Health Authority Number.\
"; }

      if(warn.length === 0){ formObj.submit(); } else { alert(warn); return false; }
      }
</script>

HTH

Hi thanks but I haven’t learned objects yet. Actually it’s the two functions I mention that I want to check as it’s an exercise I’m doing and the rest of the code is working. I’ll come back to your example when I’m more advanced.

function fieldEmpty() should be function fieldEmpty(id)

Inline event handlers are yucky.
Also, doing this will mean that people who have JavaScript disabled cannot submit the form (which is a usability fail).
Basically, you should never rely on client side validation for anything, rather it should be an added layer to assist your users (the essential validation taking place on the server).

Apart from that, I agree with the rest :slight_smile:

Well, OP did state that it is for an exercise.

If I’m developing an app for internal use only, pure JS validation is sufficient. If developing something available to the public, then hell yeah, I use client-side for primary validation, then server-side for those who do disable JS.

Also, doing this will mean that people who have JavaScript disabled cannot submit the form (which is a usability fail).

Some people disable JS to intentionally bypass validation - these are the users that give me the reason to do it that way.

Also, if a user has JS disabled because they don’t like JS, then they must not want anything to do with my site/app, and I’m okay with that.

Hi, I just wanted to know what’s wrong with my code, for the exercise I was doing. Once I understand this basic form, I’ll start writing my own. Thanks.

I think that using “this” is problematic. I recommend either passing the object to the function as an argument (my preference), or creating a global var (outside the function) that points to that object (var fore = document.forms[“contactform”].forename).

I can’t use global variables. And as I mentioned before, I don’t know objects yet. And I want to work with this exercise I did last week. It’s just the error I have that don’t know what it is.

Then create the var inside the function, making it a local var instead of global.

That’s just a fraction of the code my tutor wrote in class on Tuesday. I’m just trying to debug it. There’s a function for each check: blank space, length, characters, patterns, etc, and then for each field, you have a function that applys 3 different test to that field.

I question what your tutor is teaching. This all seems very… complex (for such a simple process) and out of date. To me. Others may disagree with me.

As far as troubleshooting your code - you’ve got functions calling functions (which, in and of itself, isn’t incorrect) without passing arguments, expecting “this” to reliably refer to whatever input called it (which I’m not so sure it always will.)

If I’m not mistaken - and I could be - but I think your tutor is conflicting him/herself by saying “no global variables” because (correct me if I’m wrong, somebody) “this” is a global.

This is the complete exercise the tutor was doing (University of London) on Tuesday if you want to know. The tutor gave this introduction to forms.
I wanted from the start to configure a validator object and loop over everything including spreading the error messages - but they haven’t covered objects yet. Anyway, I can post that later.
I realize this code is far from ideal, but I just want to know why is not working. So I can happily discard it completely and do something revolutionary for a beginner.


function main(){
    document.getElementById("contactform").onsubmit = validateAll; 
    document.getElementById("forename").onblur = validateNameField;
    document.getElementById("surname").onblur = validateNameField;
    document.getElementById("telephone").onblur = validatePhoneField; 
}

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

function validateNameField(){
    var test1 = fieldEmpty(this);
    var test2 = fieldLength(this, 2, 50);
    var test3 = fieldCharacters(this, "A");
    var result = test1&&test2&&test3;
    return result;     
}

function validatePhoneField(){
    var test1 = fieldEmpty(this);
    var test2 = fieldLength(this,11,11);
    var test3 = fieldCharacters(this,"N");
    var result = test1&&test2&&test3;
    return result;     
}

function fieldEmpty(id){
    var valid = true;
    if (id.value==" ") {
        valid=false;
        alert("Blank"); 
    }
    return valid;     
}

function fieldLength(id,min,max){
    var valid = true;
    var lng = id.value.length;
    if (lng < min || lng > max) {
        valid = false;
        alert("Length");
    }
    return valid;     
}

function fieldCharacters(id,character){
    var letters = /[a-zA-Z]/;
    var numbers = /[0-9]/;
    var patternTest;
    var valid = true;
    
    /* change pattern Test depending on value of character parameter */
    if (character =="N") {
        patternTest = numbers; 
    } else if(character == "A") {
        patternTest = letters; 
    }
    
    /* test pattern */
    
    valid = patternTest.test(id.value);
    if (!valid) {
     alert("pattern fail"); 
    }
    return valid; 
    
}

/* function left over from first exercise */ 

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; 





<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Contact Form</title>
    <link href="contactform-session9-2.css" rel="stylesheet">
    <script src="contactform-session9-2.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="forename" required>
                <span id = "forenamefieldmessage" class="infomessage">Your name should be at least two alpha characters</span>
            <label for="surname">Last Name <em>*</em></label>
                <input id="surname" required>
                <span id = "surnamefieldmessage" class="infomessage"></span>
            <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>
                <span id = "title" class="infomessage"></span>
        </fieldset>
        <!-- Contact details -->
        <fieldset>
            <legend>Contact Details</legend>  
            <label for="telephone">Telephone</label>
                <input id="telephone">
                <span id = "errorMessage"></span>
            <label for="email">Email <em>*</em></label>
                <input id="email" type="email" required>
                <span id = "email" class="emailfield"></span>
        </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>
                <span id = "health-number-field" class="infomessage"></span>
        </fieldset>
        <p><input type="submit" value="Submit" id=submit></p>
    </form>
</body>
</html>



Thanks in advance.

I copied/pasted your code into a .htm file, locally, and ran it in IE10 with Developer Tools running in debugging mode. Absolutely no error messages.

Normally, I would think that something was breaking JavaScript (either at load, or during a blur or submit), but that apparently is not the case.