Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to create a generic Javascript function that I can use to verify different field values and output the error message alongside the correct field. I would like to create an efficient, reusable function, but I am new to Javascript and am unsure how to proceed.

Advise on how to change my validation function to validate both firstname and lastname would be appreciated.

My code so far:

function validateForm() {
    var x = document.forms["myForm"]["firstname"].value;
    var reg_azs = /^[^a-zA-Z\-']+$/;
    var reg_oal = "!#$%^&*()+=[]\\\';,{}|\":<>?123456790";

    if (x == null || x == "") {
        document.getElementById("fn").innerHTML = "This fuild is required.";
        return false;
    } else if (reg_azs.test(firstname.value)) {
        document.getElementById("fn").innerHTML = "Only alphabetic letters.";
        return false;
    } else {
        for (var i = 0; i < x.length; i++) {
            if (reg_oal.indexOf(x.charAt(i)) != -1) {
                document.getElementById("fn").innerHTML = "Only alphabetic letters.";
                return false;
            }
        }
    } else {
        document.getElementById("fn").innerHTML = "correct";
        return true;
    }
}

My Form:

<form name="myForm" action="connection.php" method="post">
    <label for='firstname'>First Name:</label>
    <input type="text" id="firstname" name="firstname" onchange="return validateForm()" />
    <err1 id="fn"></err1>
    <br>  

    <label for='lastname'>Last Name:</label>
    <input type="text" id="lastname" name="lastname" onchange="return validateForm()" />
    <err1 id="ln"></err1>
    <br>
</form>
share|improve this question
1  
The html is invalid as there is no err1 tag specified in the standard. –  Andreas Sep 16 '12 at 22:31
    
Check my answer to this question stackoverflow.com/questions/12434948/…, it might help to keep it DRY. –  elclanrs Sep 16 '12 at 22:32
1  
"Less code" does not mean "faster". Quite often, abbreviating code to the point of obfuscation makes it slower, and certainly harder to maintain. –  RobG Sep 16 '12 at 23:06
    
It is a bad idea to restrict someone's name to just ASCII letters. In addition to the several billion people who spell their names with Chinese letters, dozens of O'Shays and O'Shanters around the world get annoyed not being able to type their name right. This kind of restriction is usually the sign of a basic bad design. –  Jeremy J Starcher Sep 16 '12 at 23:29

1 Answer 1

up vote 1 down vote accepted

I would make the function accept a few parameters: id of the element being examined, id of the element to show the error message, and then maybe a string of regular expression to validate it (could be optional).

From there, you could set x as:

var x=document.getElementById(param1).value;

and everytime you reference the error element, like this:

document.getElementById("fn")

change it to:

document.getElementById(param2)

So your function declaration would look like this:

function validateForm(param1, param2) {

And when you call it, it would look like:

onchange="return validateForm('firstname', 'fn');"
onchange="return validateForm('lastname', 'ln');"

and so on.

You'd probably want to change the parameter names as well, param1 and param2 are just for example, and might be better as targetElem and errorLabel, respectively.

UPDATE:

This design is also narrow-minded, such that you have to call validateForm for every element you want to validate. An alternative, to allow multiple elements to be validated with one function call is to use an array of objects, where each object has a form like:

{"element_id": "whatever", "error_id": "whatever"}

But in your function, you would loop through the single parameter (an array), and access each one like so:

for (var i = 0; i < param1.length; i++) {
    // Use param1[i]["element_id"] and param1[i]["error_id"]
}

In this case, you can add extra things to each object, to allow for specific validation rules, such as not being empty, at least a certain length, no longer than a certain length, etc. ...and in the loop, you'd have to check for those things being present.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.