Jump to content

Form Validate Funcion


Lautarox

Recommended Posts

I wrote this function and it's not working, don't know why..

function valitadeForm(elementID) {
var form = document.getElementByID(elementID);
var isComplete = true;
for(var i=0;i<form.lenght;i++) {
	if(form.element[i].name != "email") {
		if(form.element[i].value == null || "") {
			form.element[i].value = "Falta Rellenar Campo";
			isComplete = false;
		}
	}
	else {
		var apos=form.element[i].value.indexOf("@");
		var dotpos=form.element[i].value.lastIndexOf(".");
		if(apos <1 || dotpos-apos < 2) {
			form.element[i].value = "E-mail Incorrecto";
			isComplete = false;
		}
	}
}
return isComplete;
}

I'm calling it like this

<FORM id="addcomment" method="POST" enctype="application/x-www-form-urlencoded" action="?go=addcomment" onsubmit="return validateForm('addcomment')">

Any suggestions will be appreciated, thanks

Link to comment
Share on other sites

A few things:

 

1. No need to pass the form ID to the function. Instead, use 'this' to pass the form object. Then you don't need to create the form object using

var form = document.getElementByID(elementID);

 

2. This if statement is part of your problem

if(form.element[i].value == null || "")

Instead you need to use this:

if(form.element[i].value == null || form.element[i].value == "")

 

3. Also, iterrating through each element is probably not a good idea, because ANY element in the form would be validated, such as the submit button. It is better, in my opinion, that you explicitly validate each field that needs to be validated

 

4. Here is a better email validation script:

function validEmail(emailStr)
{
    //Return true/false for valid/invalid email
    formatTest = /^[\w`\-=~!#$%^&*'+{}|'/?]+(\.[\w`\-=~!#$%^&*'+{}|'/?]+)*@[-a-z\d]{2,}(\.[-a-z\d]{2,})*\.[a-z]{2,6}$/i
    lengthTest = /^(.{1,64})@(.{4,255})$/
    return (formatTest.test(emailStr) && lengthTest.test(emailStr));
}

 

Here is what I would do:

function valitadeForm(formObj)
{
    var isComplete = true;

    for(var i=0;i<formObj.lenght;i++)
    {
        switch(formObj.element[i].name)
        {
            case 'field1name':
            case 'field2name':
            case 'field3name':
            case 'field4name':
                if (emptyField(formObj.element[i].value))
                {
                    formObj.element[i].value = "Falta Rellenar Campo";
                    isComplete = false;
                }
                break;
            case 'email':
                if (!validEmail(formObj.element[i].value))
                {
                    formObj.element[i].value = "E-mail Incorrecto";
                    isComplete = false;
                }
                break;
        }
    }

    return isComplete;
}

function emptyField(fieldValue)
{
    //Trim white-space characters from the value
    var trimmedValue = fieldValue.replace(/^\s+|\s+$/g,'');
    return (trimmedValue == "");
}

 

<FORM id="addcomment" method="POST" enctype="application/x-www-form-urlencoded" action="?go=addcomment" onsubmit="return validateForm(this)">

Link to comment
Share on other sites

I agree with the advice that mjdamato gave you. I would handle it a bit differently though.

 

Id write rules for certain types of checks, then i'd add the rule name to the class of the input/raido button/check box

 

Id remove the inline js in the form code and write a listener in the head of the document that is fired onload.

 

And instead of implicitly defining which fields should be checked, id add a class name that defines the type of check and loop through the form's elements and check those with the required class name. I would validate those against little validation functions defined in an object literal

 

check out this example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<title>regex</title>
<script type="text/javascript" charset="utf-8">
    /** 
         * define your simple validation methods in an object literal and return a boolean value for each method
         */
        validate = {
            validateEmail: function(email){
                var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                return filter.test(email);
            }
        };

        onload = function(){
            var form = document.getElementById('form_id');
            var classes = ['validateEmail', 'validateShortDate']; //array defining which classes to check make these the same as the method to check against
            var inputs = form.getElementsByTagName('input');

            form.onsubmit = function(){
                var process = true;
                
                /**
                 * loop through the form inputs only selecting the ones with the defined class names
                 */
                for(var i = 0, l = inputs.length; i < l; i++){
                    var classname = inputs[i].className;

                    if(validate[classname]){
                        process = validate[classname](inputs[i].value); //call the function
                    } 
                }
                
                //you want to return process to tell the form to submit or not
                //return process;
                return false;
            };
        };
</script>
</head>

<body>
    <form action="" id="form_id" method="post">
        <input type ="text" value="" name="email" class="validateEmail" />
        <input type="submit" value="submit" name="submit" />
    </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.