0

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>
4
  • 1
    The html is invalid as there is no err1 tag specified in the standard. Commented Sep 16, 2012 at 22:31
  • Check my answer to this question stackoverflow.com/questions/12434948/…, it might help to keep it DRY. Commented Sep 16, 2012 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. Commented Sep 16, 2012 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. Commented Sep 16, 2012 at 23:29

1 Answer 1

1

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.

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

Comments

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.