1

Hi there I am really stuck on this and since I am a javscript beginner this boggles my mind.

Is there someone who knows how to write the following javascript form validation? I am sure that it is very simple, but I can not figure this one out to save my life.

Thank you for you sharing your knowledge.

I need to write WITHOUT jquery the following form validation. Whenever an error is encountered, prevent the form from being submitted. I need to use the window.onload function to assign a validation callback function. There are 4 inputs which get validated by the javascript code. Also the javascript needs to be in its own file.

Validation Rules are as follow:

INPUT: Username; Required (yes); Validation (Must be 5-10 characters long). INPUT: Email; Required (yes); Validation (Must have an @ sign, must have a period). INPUT: Street name; Required (no); Validation (Must start with a number). INPUT: Year of birth; Required (yes); Validation (must be numeric).

My code looks as follow:


HTML:


<!DOCTYPE html>
<html>
<head>


<script defer="defer" type="text/javascript" src="form.js"></script>


</head>
<body>
<form action="fake.php">
    Username*: <input type="text" class="required" name="u"/><br/>
    Email*: <input type="text" class="required" name="p"/><br/>
    Street address: <input type="text" class="numeric" name="s"/><br/>
    Year of birth*: <input type="text" class="required numeric" name="b"/><br/>


    <input type="submit"/><br/>
</form>
</body>
</html>

JS

document.forms[0].elements[0].focus();

document.forms[0].onsubmit=function(){

for(var i = 0; i < document.forms[0].elements.length; i++){

var el = document.forms[0].elements[i];

if((el.className.indexOf("required") != -1) && 
  (el.value == "")){

alert("missing required field");
 el.focus();
el.style.backgroundColor="yellow";
 return false;
}

if((el.className.indexOf("numeric") != -1) && 
 (isNaN(el.value))){


alert(el.value + " is not a number");
 el.focus();
el.style.backgroundColor="pink";
 return false;              
  }
 }
}
7
  • I don't really see any problems here? demo fiddle: jsfiddle.net/Nern7 Commented Mar 29, 2013 at 3:43
  • Are you having any specific problems / errors / issues with this code? Commented Mar 29, 2013 at 3:46
  • Sorry - Maybe I should have been a little more specific. 1) The username must be between 5-10 characters. doesnt work. I don't know how to do this one. 2)The email block doesn't validate for an "@" and a "." I also don't know how to do this one. 3) The street address must start with a number. That doesn't work. Commented Mar 29, 2013 at 3:53
  • Why don't you create a form validation object. If you need a sample let me do some work to make your task easy. Actually it has taken help from tutplus example. I can't remember the link though. Commented Mar 29, 2013 at 4:00
  • Hi there, I appreciate your help. I don't know how to create a form validation object. Could you help me if possible? Thank you Commented Mar 29, 2013 at 4:05

3 Answers 3

1

without changing much of your code ... updated your code for other validation like length (needs a class verifylength to validate length) and so on....

try this

HTML

<form action="fake.php">Username*:
<input type="text" class="required verifylength" name="u" />
<br/>Email*:
<input type="text" class="required email" name="p" />
<br/>Street address:
<input type="text" class="numeric" name="s" />
<br/>Year of birth*:
<input type="text" class="required numeric" name="b" />
<br/>
<input type="submit" />
<br/>
</form>

JAVASCRIPT

document.forms[0].elements[0].focus();
document.forms[0].onsubmit = function () {
for (var i = 0; i < document.forms[0].elements.length; i++) {
    var el = document.forms[0].elements[i];
    if ((el.className.indexOf("required") != -1) && (el.value == "")) {
        alert("missing required field");
        el.focus();
        el.style.backgroundColor = "yellow";
        return false;
    } else {
        if (el.className.indexOf("verifylength") != -1) {
            if (el.value.length < 5 || el.value.length > 10) {
                alert("'" + el.value + "' must be 5-10 charater long");
                el.focus();
                el.style.backgroundColor = "pink";
                return false;
            }
        }
    }

    if (el.className.indexOf("email") != -1) {
        var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
        var emailTest = regEx.test(el.value);
        if (!emailTest) {
            alert("email not valid");
            el.focus();
            el.style.backgroundColor = "yellow";
            return false;
        }
    };

    if ((el.className.indexOf("numeric") != -1) && (isNaN(el.value))) {
        alert(el.value + " is not a number");
        el.focus();
        el.style.backgroundColor = "pink";
        return false;
    }
 }
}

working fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

something alongs the lines of...

//username 5-10 chars
var uVal = document.getElementsByTagName("u").value;
if (uVal.length < 5 || uVal.length > 10) return false;

//email needs @ and .
var eVal = document.getElementsByTagName("p").value;
if !(eVal.match('/.*@.*\./g')) return false;

//street starts w/ num
var sVal = document.getElementsByTagName("s").value;
if !(sVal.match('/^[0-9]/g')) return false;

i think the regex is off + untested :)

5 Comments

Thank you this is a great improvement to what I already have.
Another quick question and I know this is silly, but should I overwrite my existing js with the above code? I think the answer is yes, but which part? May I ask that you give me sample? Thank you VERY MUCH for your HELP!!!
hey. If its just a university/college lab, id recommend replacing your code with the above. If you do, make sure you know what this code does because it will probably appear in an exam :)
Hi Micheal,Thank you. One more question..? Sorry for all the questions, but you seem to be very knowledgeable. If I would replace my existing JS file with your code I am still missing the Validation for "Year of Birth". The Validation must be numeric only. Any clue to how I can do that? And one more Q? do I keep the document.forms[0].elements[0].focus(); document.forms[0].onsubmit=function(){ for(var i = 0; i < document.forms[0].elements.length; i++){}
heya. no idea how to do the all-numeric validation. remove document.forms[0].elements[0].focus(); and the for loop. cheers.
0

Here is your javascript validation object in work. Hope you can make some modification according to your need.

Style

<style>
    .valid {border: #0C0 solid 1px;}
    .invalid {border: #F00 solid 1px;}
</style>

HTML Form

<div>
    <form id="ourForm">
        <label>First Name</label><input type="text" name="firstname" id="firstname" class="" /><br />  
        <label>Last Name</label><input type="text" name="lastname" id="lastname" class="" /><br />  
        <label>Username</label><input type="text" name="username" id="username" class="" /><br />
        <label>Email</label><input type="text" name="email" id="email" class="" /><br />  
        <input type="submit" value="submit" class="" />  
    </form>
</div>

Call script before closing tag

<script src="form_validation_object.js"></script>

form_validation_object.js

/*
 to: dom object
 type: type of event
 fn: function to run when the event is called
 */
function addEvent(to, type, fn) {
    if (document.addEventListener) { // FF/Chrome etc and Latest version of IE9+
        to.addEventListener(type, fn, false);
    } else if (document.attachEvent) { //Old versions of IE. The attachEvent method has been deprecated and samples have been removed.
        to.attachEvent('on' + type, fn);
    } else { // IE5
        to['on' + type] = fn;
    }
}

// Your window load event call
addEvent(window, 'load', function() {
    /* form validation object */
    var Form = {
        validClass: 'valid',
        inValidClass: 'invalid',
        fname: {
            minLength: 1,
            maxLength: 8,
            fieldName: 'First Name'
        },
        lname: {
            minLength: 1,
            maxLength: 12,
            fieldName: 'Last Name'
        },
        username: {
            minLength: 5,
            maxLength: 10,
            fieldName: 'Username'
        },
        validateLength: function(formElm, type) {
            //console.log('string = ' + formElm.value);
            //console.log('string length = ' + formElm.value.length);
            //console.log('max length=' + type.maxLength);
            //console.log(Form.validClass);
            if (formElm.value.length > type.maxLength || formElm.value.length < type.minLength) {
                //console.log('invalid');
                //alert(formElm.className);
                if (formElm.className.indexOf(Form.inValidClass) == -1) {
                    if (formElm.className.indexOf(Form.validClass) != -1) {
                        formElm.className = formElm.className.replace(Form.validClass, Form.inValidClass);
                    } else {
                        formElm.className = Form.inValidClass;
                    }
                }

                //alert(formElm.className);
                return false;
            } else {
                //console.log('valid');
                //alert(formElm.className.indexOf(Form.validClass));
                if (formElm.className.indexOf("\\b" + Form.validClass + "\\b") == -1) { // regex boundary to match whole word only  http://www.regular-expressions.info/wordboundaries.html
                    //formElm.className += ' ' + Form.validClass;
                    //alert(formElm.className);
                    if (formElm.className.indexOf(Form.inValidClass) != -1)
                        formElm.className = formElm.className.replace(Form.inValidClass, Form.validClass);
                    else
                        formElm.className = Form.validClass;
                }
                return true;
            }
        },
        validateEmail: function(formElm) {
            var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
            var emailTest = regEx.test(formElm.value);
            if (emailTest) {
                if (formElm.className.indexOf(Form.validClass) == -1) {
                    formElm.className = Form.validClass;
                }
                return true;
            } else {
                formElm.className = Form.inValidClass;
                return false;
            }
        },
        getSubmit: function(formID) {
            var inputs = document.getElementById(formID).getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].type == 'submit') {
                    return inputs[i];
                }
            }
            return false;
        }
    }

    /* call validation object */
    var ourForm = document.getElementById('ourForm');
    var submit_button = Form.getSubmit('ourForm');
    submit_button.disabled = 'disabled';

    function checkForm() {
        var inputs = ourForm.getElementsByTagName('input');
        if (Form.validateLength(inputs[0], Form.fname)) {
            if (Form.validateLength(inputs[1], Form.lname)) {
                if (Form.validateLength(inputs[2], Form.username)) {
                    if (Form.validateEmail(inputs[3])) {
                        submit_button.disabled = false;
                        return true;
                    }
                }
            }
        }
        submit_button.disabled = 'disabled';
        return false;
    }

    checkForm();
    addEvent(ourForm, 'keyup', checkForm);
    addEvent(ourForm, 'submit', checkForm);

});

Working example at JSBin
http://jsbin.com/ezujog/1

4 Comments

THANKS YEGYA YOUR WORKING SAMPLE WAS OF GREAT HELP. I STILL NEED TO FIGURE OUT HOW TO MAKE IT WORK FOR ME THOUGH.
Pretty glad to help you pal. I strongly suggest you to go through the sample code line by line, try to understand how it is functioning and read the javascript topics like javascript object, prototype, functions, closures, classes etc (if you already don't know about them), and I can guarantee your coding style and scripting knowledge will be in next level within a month. U will find it easy working with javascript libraries like jquery, dojo, prototypejs etc.
@Yegya—don't test document.attachEvent, test the object passed to the function: to.attachEvent. Rather than all those nested ifs, consider a loop instead.
@RobG It was just intended for proving him some basic idea on the power of object oriented javascript. Agreed on ur loop part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.