Question

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>
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top