Jump to content

Form validation problem


iAmiAdam

Recommended Posts

I'm using javascript to validate my form, as usual. But for some reason, it doesn't want to work now and I've got no idea why, I've tried changing the form into a function to display it and all sorts, but can't figure it out. Initially, I was including the javascript in a seperate file but then incorporated it in an attempt to make it work, to no avail.

 

Any help is appreciated, code below.

 

<html>
<head>
<link rel="stylesheet" href="styles.css" type="text/css" />
<script type="text/javascript">

function notEmpty(input) {
    var fieldset = input.parentNode;
    var txt = input.value;
    if (txt === " "){
        fieldset.classname = "errmsg";
        return false;
    }else{
        fieldset.classname = "box";
        return true;
    }
}

function injection(input) {
    var fieldset = input.parentNode;
    var txt = input.value;
    if (txt.search("'") || txt.search("$")){
        fieldset.classname = "errmsg";
        return false;
    }else{
        fieldset.classname = "box";
        return true;
    }
}

function plength(input) {
    var fieldset = input.parentNode;
    var txt = input.value;
    if (txt.length > 6 && txt.length < 12){
        fieldset.classname = "box";
        return true;
    }else{
        fieldset.classname= "errmsg";
        return false;
    }
}

function validate() {
    var callsign = document.getElementById('aesid');
    var pword = document.getElementById('pword');
    if (notEmpty(callsign) == true){
        if(notEmpty(pword) == true){
            if(injection(callsign) == true){
                if(injection(pword) == true){
                    if(plength(pword) == true){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }else{
        return false;
    }
}

</script>
</head>
<?php

error_reporting(0);

/**
* @author Adam Smith 
* @copyright 2012
*/

//This file logs the user in.

if(isset($_POST['aesid'])){
    $aid = $_POST['aesid'];
}

function displayForm() {
    echo '<form name="login" action="" method="POST" onsubmit="validate();">';
    echo '<div id="loginlabel">';
    echo            'AeroStar ID: (AES000)';
    echo '</div>';
    echo '<fieldset>';
    echo '<div id="loginfield">';
    echo        '<input type="text" name="aesid" maxlength="7" value="'.$aid.'">';
    echo '</div>';
    echo '<span class="box">Aerostar IDs follow the pattern AES000.</span>';
    echo '</fieldset>';
    echo '<div class="clearboth"></div>';
    echo '<div id="loginlabel">';
    echo        'Password:';
    echo '</div>';
    echo '<fieldset>';
    echo '<div id="loginfield">';
    echo            '<input type="password" name="pword">';
    echo '</div>';
    echo '<span class="box">Passwords are between 6 and 12 characters and can not contain apostrophies or $.</span>';
    echo '</fieldset>';
    echo '<div class="clearboth"></div>';
    echo '<div id="loginsubmit">';
    echo            '<input type="submit" name="subbtn" value="Login">';
    echo '</div>';
    echo '</form>';
}

if($_POST['subbtn']){
    displayForm();
}else{
    displayForm();
}

?>
</html>

Link to comment
Share on other sites

When trying to debug JavaScript errors I find it much easier to work from the HTML source code. So, access the file above in a browser and then export the source to a flat HTML file. That way you don't have to worry about mixing JS and PHP errors. Once you get the page working then you can migrate the correct code into the PHP script.

 

OK, here are a few things I see:

 

1. You are missing BODY tags. Although this is not the source of your problem it doesn't help to have non-conforming code.

2. You should revise your validation logic so it doesn't have all those nested if statemetns. Instead do a negative check and return false for each validation. Much easier to read.

3. You are referencing field using getElementById(), but you failed to provide an ID to the fields!

4. Your notEmpty() validation returns false if the input is a single space - not if it didn't have a value

5. Your validation functions are attempting to reference the parent node - but in each instance the parent node is not the object you actually want. In some you want the span after the field with the display text in others you want the fieldset. Neither is the parent node of the input fields.

 

Basically I see so much wrong in that code it would take me quite a while to find all the problems.

 

EDIT: Some other issues:

 

6. Although you are trying to return false in the function you are not returning false for the form, thus the form will ALWAYS submit

7. When trying to change the class of an object it needs to be "className", not "classname";

Link to comment
Share on other sites

Here's a question, why are you doing character and length checks on a login page? The user should already have thier username and password so stating requirements such as those have no value. You should only do those types of checks in the creation process. By giving information such as length requirements and character requirements on the login page you are only providing information to users who might be trying to hack into your site.

Link to comment
Share on other sites

Also there is no valid reason to restrict apostrophes or dollar signs from the user input to prevent SQL Injection.

 

Basically, you need to start over. Do ONE thing and make it work. Then add ONE more thing. Make it work as well as the previous function. Then add ONE more thing and make it work as well as the first two things. And so on...

 

Do not try to build a complete solution in one go. I have to assume you copied that code above from somewhere and pasted it into your page expecting it to work. That's fine to use existing code but you have to understand what it is doing so you can make the appropriate modifications for your situation.

Link to comment
Share on other sites

You're not understanding what I'm saying:  Don't have a "backup solution," have a real solution.  Javascript is not a real validation solution.  It can never be.  Ever.  Users can get around your javascript.  Whatever you put in javascript is "fancy", it is not real functionality.  Your back-end code most do the real validation.

Link to comment
Share on other sites

No, it was all written myself, I've just never used javascript before.

 

I find that very difficult to believe. There are so many issues of so many variations I can't see how someone would progress so far with none of it working. But, no matter, I'm still willing to help. As I stated previously, you need to do one thing at a time. As nogray stated the onsubmit trigger needs to have a "return" statement in it. If you return false the form is not submitted. So, the standard is to do something such as onsubmit="return validate();" and have the validation function return true if validation passes (form is submitted) or false if validation fails (form does not submit). Start over on your validation function and only do ONE validation. Don't even worry about the fancy changing of the classes. Once that works then move on to adding additional features or additional validations.

Link to comment
Share on other sites

OK, here is a complete rewrite of your code in a more logical format. I did this from the rendered page (i.e. after the PHP code was parsed). So you would need to implement the changes in your PHP file. I also added some sample classes that you referenced for testing so you should take those out. But, you can run the complete code below as a flat HTML file to see if it works as you need it to.

 

Just a couple notes though:

 

If you have a minimum and maximum length requirement for a field, so you really need to verify that the user input something? As I stated previously you really shouldn't be doing a min/max length check on a login form since the user is not creating the values. But, if you do that type of check on a field, then a check to see if the field is empty is redundant.

 

As stated previously there is no valid reason for restricting ' and & for SQL Injection purposes.

 

<html>
<head>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style>

.box { background-color: yellow; }
.errmsg { background-color: red; }
</style>
<script type="text/javascript">

// *** VALIDATION FUNCTIONS ***

function isEmpty(fieldValue)
{
return (fieldValue=='');
}

function validLength(fieldValue, minLength, maxLength)
{
    return (fieldValue.length >= minLength && fieldValue.length <= maxLength)
}

function invalidCharacters(fieldValue, invalidChars)
{
    var regEx = invalidChars.split('').join('|');
    return (fieldValue.search(regEx)!=-1)
}

// **** HELPER FUNCTIONS ***

function getFieldValue(fieldID)
{
    var fieldObj = document.getElementById(fieldID);
    //Trimm the value and replace in field
fieldObj.value = fieldObj.value.replace(/^\s+|\s+$/g,'');
    //Return the trimmed value
return fieldObj.value;
}


// **** VALIDATION FUNCTION ***

function setClass(objID, className)
{
    document.getElementById(objID).className = className;
    return;
}

function validate()
{
    var validForm = true;

    //Get the field input values (and trim them)
var aesidValue = getFieldValue('aesid');
var pwordValue = getFieldValue('pword');

    //Set all text descriptions to non-error condition
    setClass('aesid_text', 'box');
setClass('pword_text', 'box');

//Perform validations of AESID field
    if (isEmpty(aesidValue)) { setClass('aesid_text', 'errmsg'); validForm = false; }
    else if(!validLength(aesidValue, 6, 12)) { setClass('aesid_text', 'errmsg'); validForm = false; }
else if(invalidCharacters(aesidValue, "'&")) { setClass('aesid_text', 'errmsg'); validForm = false; }

//Perform validations of password field
    if (isEmpty(pwordValue)) { setClass('pword_text', 'errmsg'); validForm = false; }
    else if(!validLength(pwordValue, 6, 12)) { setClass('pword_text', 'errmsg'); validForm = false; }
else if(invalidCharacters(pwordValue, "'&")) { setClass('aesid_text', 'errmsg'); validForm = false; }

    return validForm;
}

</script>
</head>
<body>

<form name="login" action="" method="POST" onsubmit="return validate();">
<div id="loginlabel">AeroStar ID: (AES000)</div>
<fieldset>
<div id="loginfield"><input type="text" name="aesid" id="aesid" maxlength="7" value=""></div>
<span class="box" id="aesid_text">Aerostar IDs follow the pattern AES000.</span>
</fieldset>

<div class="clearboth"></div><div id="loginlabel">Password:</div>
<fieldset>
<div id="loginfield"><input type="password" name="pword" id="pword"></div>
<span class="box" id="pword_text">Passwords are between 6 and 12 characters and can not contain apostrophies or $.</span>
</fieldset>

<div class="clearboth"></div>
<div id="loginsubmit"><input type="submit" name="subbtn" value="Login"></div>
</form>

</body>
</html>

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.