Jump to content

JS validation


Stefany93

Recommended Posts

Hello fellows,

 

I am building a client - side contact form validation with JS. The problem is that that I want when the user inputs the wrong input, basically, a text next to the input box to appear with the appropriate error message when the user clicks "submit". So far so good, but the main issue occurs when the user clicks "submit" multiple times and the error message repeats itself which is kind of lame. 

Tried to solve it for a couple of hours yesterday, until I failed miserably...

So could you please tell me a way to make it the error message to appear only once, regardless how many times "submit" has been pressed?

 

Here is the code written so far:

 

 

 

 
function validate_form(name_field, email_field, text_area){
var fieldset_name = document.getElementById("fieldset_name");
var fieldset_email = document.getElementById("fieldset_email"); 
var fieldset_message = document.getElementById("fieldset_message");
var re = /^[a-z]+[a-z0-9.]+@{1}[a-z0-9\-]+[.]{1}[a-z]{1,5}[a-z.]{1,5}?[a-z]$/i;
 
var name_error = document.createTextNode("Please populate your name!"); 
var email_error = document.createTextNode("Please enter a valid email!");
var message_error = document.createTextNode("Please populate your message");
 
if(name_field.value.length <= 2){
fieldset_name.appendChild(name_error);
return false;
}
}

Edited by Stefany93
Link to comment
Share on other sites

Instead of using "createTextNode" and "appendChild" to add the error message, I would create an empty span next to each input field with an ID associate with each field. Then if there is an error, populate the span with the error message.

 

Plus, it looks like to stop at the first error instead of showing all the errors which is a poor implementation in my opinion.

Edited by Psycho
Link to comment
Share on other sites

@Jessica, your solution to the problem was pure genius, thank you very much!

@Psycho, thank you very much for telling me that all of the errors need to be displayed, not the program to stop at the first one encountered. 

 

About your second advice, I was actually thinking of implementing some elements next to the input box just with IDs without values, but I have had programmers telling me that this is plain wrong and a bad programming practice because the server loads the empty <span></span> elements without actually having to use them if the user inputs their data correctly and thus making them useless, that is why, I have been told, the best way to add a text into the document with JS is just to create elements and text nodes on the fly.

 

Here is the complete code. If someone has any comments on it, I will be most happy to read them, thank you.

 

 

 
clicked = false;
window.onload = function(){
document.forms[0].onsubmit = function(){
name_field = document.getElementById("name_field");
email_field = document.getElementById("email_field");
text_area = document.getElementById("text_area");
 
if(clicked === false){
clicked = true;
var fieldset_name = document.getElementById("fieldset_name");
var fieldset_email = document.getElementById("fieldset_email"); 
var fieldset_message = document.getElementById("fieldset_message");
var re = /^[a-z]+[a-z0-9.]+@{1}[a-z0-9\-]+[.]{1}[a-z]{1,5}[a-z.]{1,5}?[a-z]$/i;
var there_is_error;
 
var name_error = document.createTextNode(" Please populate your name! "); 
var email_error2 = document.createTextNode(" Please enter your email! ");
var email_error = document.createTextNode(" Please enter a valid email! ");
var message_error = document.createTextNode(" Please populate your message ");
 
if(name_field.value.length <= 2){
fieldset_name.appendChild(name_error);
there_is_error = true;
}
if(email_field.value.length <= 5){
fieldset_email.appendChild(email_error2);
there_is_error = true;
}
if(!re.test(email_field.value)){
fieldset_email.appendChild(email_error);
there_is_error = true;
}
if(text_area.value.length < 1){
fieldset_message.appendChild(message_error);
there_is_error = true;
}
if(there_is_error === true){
return false;
}
}
}
}
 
Link to comment
Share on other sites

Everyone is entitled to their opinion. My opinion is that some empty SPAN tags would not be an issue. It is just some simple ASCII text and wouldn't have any real effect on the time to download the page and the overhead to display the page wouldn't be affected either that anyone could ever notice. It is much more efficient to add text to an existing SPAN than adding a bunch of text nodes.

 

Also, by adding text nodes, if a user fixes one problem but makes a different error how do you remove the first error? You would now have to add an ID to those text nodes so you can remove them. By just updating a span you can clear/populate that field very simply.

 

Here is a quick/rough rewrite for one possible solution

 

<html>
<head>
<script type="text/javascript">

function validate_form(formObj)
{
    var errors = false;

    //name validation
    var nameErrText = "";
    var fieldset_name = document.getElementById("fieldset_name");
    if(fieldset_name.value.length <= 2)
    {
        nameErrText = "Please populate your name!";
    }
    if(nameErrText != "") { errors = true; }
    document.getElementById('fieldset_name_error').innerHTML = nameErrText;

    //Email validation
    var emailErrText = "";
    var fieldset_email = document.getElementById("fieldset_email");
    var re = /^[a-z]+[a-z0-9.]+@{1}[a-z0-9\-]+[.]{1}[a-z]{1,5}[a-z.]{1,5}?[a-z]$/i;
    if(!fieldset_email.value.length)
    {
        emailErrText = "Please enter an email address";
    }
    else if(!re.test( fieldset_email.value))
    {
        emailErrText = "Please enter a valid email!";
    }
    if(emailErrText != "") { errors = true; }
    document.getElementById('fieldset_email_error').innerHTML = emailErrText;

    //Message validation
    var messageErrText = "";
    var fieldset_message = document.getElementById("fieldset_message");
    if(fieldset_message.value.length < 1)
    {
        messageErrText = "Please populate your message!";
        errors = true;
    }
    if(nameErrText != "") { errors = true; }
    document.getElementById('fieldset_message_error').innerHTML = messageErrText;

    //Return true/false based upon whether there were errors
    return (!errors);
}
</script>

<style>
.error { color: #ff0000; }
</style>

</head>
<body>

    <form onsubmit="return validate_form(this);" method="POST">
    Name: <input type="text" name="fieldset_name" id="fieldset_name" />
    <span class="error" id="fieldset_name_error"></span><br>
    Email: <input type="text" name="fieldset_email" id="fieldset_email" />
    <span class="error" id="fieldset_email_error"></span><br>
    Message:<br>
    <textarea name="fieldset_message" id="fieldset_message"></textarea>
    <span class="error" id="fieldset_message_error"></span><br>
    <button type="submit">Submit</button>

</form>

</body>
</html>
Link to comment
Share on other sites

  • 2 weeks later...

Hello fellows,

 

Sorry to bother you again, but I have ran into troubles again. It's about the same JS validation script, but this time, when the user clicks the "submit" button, twice, instead of the error messages repeating like the case before, the form gets submitted to the server EVEN if there are still errors generated by the script, and I don't need to tell you how lame that is.

 

Here is the code itself, please give me some tips on how to proceed. I tried and I tried to fix this on my own, but without results:

 

 

 
// Input validation in the contact form
// The clicked variable checks whether the "submit" button has been clicked.
clicked = true;
// The onload property of the window object will collect the
// IDs of the form fieds we intend to get the get the values from
// as soon as the webpage has finished loading.
window.onload = function(){
document.forms[0].onsubmit = function(){
name_field = document.getElementById("name_field");
email_field = document.getElementById("email_field");
text_area = document.getElementById("text_area");
// If the "submit" button has been clicked, we set the "clicked" variable to false
// so that our JS errors won't be repeated. 
if(clicked === true){
clicked = false;
// Here we take the IDs from the fieldset elements of the form 
// we are conducting the check on. Later on, we shall append 
// text nodes to these fieldset elements as children 
// and in that way we shall display the errors
// our user might have allowed.
var fieldset_name = document.getElementById("fieldset_name");
var fieldset_email = document.getElementById("fieldset_email"); 
var fieldset_message = document.getElementById("fieldset_message");
// Our regular expression, we are going to need it later when we validate the 
// email address of the user.
var re = /^[a-z]+[a-z0-9.]+@{1}[a-z0-9\-]+[.]{1}[a-z]{1,5}[a-z.]{1,5}?[a-z]$/i;
// Due to the lack of a better idea, the variable there_is_error 
// is just defined and it will be given the value of true 
// every time there is an error with the user input.
var there_is_error;
// Here we declare the error messages our user is going to get
// if he has populated the wrong data in the mandatory fields of 
// our contact form. 
var name_error = document.createTextNode(" Please populate your name! "); 
var email_error2 = document.createTextNode(" Please enter your email! ");
var email_error = document.createTextNode(" Please enter a valid email! ");
var message_error = document.createTextNode(" Please populate your message! ");
// If the name field is less than 2 characters, diplay an error. 
if(name_field.value.length <= 2){
fieldset_name.appendChild(name_error);
there_is_error = true;
}
// If the email is less than 5 characters, display an error
if(email_field.value.length <= 5){
fieldset_email.appendChild(email_error2);
there_is_error = true;
}
// If the email is not a proper one, i.e. missing an "@" symbol
// and other typical email address character, or if it containt 
// characters unrepresentative for an email address
// display an error. We check all that with the regular expression
// we had declared earlier with the "re" variable.
if(!re.test(email_field.value)){
fieldset_email.appendChild(email_error);
there_is_error = true;
}
// If the message body is not populated at all,
// display an error
if(text_area.value.length < 1){
fieldset_message.appendChild(message_error);
there_is_error = true;
}
// If the "there_is_error" variable evaluates true,
// that means that there the user has entered incorrect information
// at some point, and what we do next is that we return false,
// which prevents the form to be submited to the server
// where it will be handled by some server side programming language.
if(there_is_error === true){
return false;
}
}
}
}
 
Link to comment
Share on other sites

I would agree with Psycho on adding empty spans for the error messages and populate them when needed. If you don't want them in your html, you can create the spans on the fly using javascript. You don't need to track the user clicks because that will simply submit the form when someone click twice. What you need is to clear all the error messages at the beginning of your validation function and check the fields. If you just create text nodes, it will be hard to track down the error messages.

Edited by nogray
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.