0

I have this chunk of code [sourced from different user on this site—thanks!] that I need to modify so that I can check multiple fields instead of just one. I'm not sure if I should be adding arguments to the second function or turn the variable checkString to an array.

function getField(fieldType, fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i = 0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

function checkField() {
    var checkString = getField('input', 'fieldtocheck').value;
    if (checkString != "") {
        if (/[^A-Za-z\d]/.test(checkString)) {
            alert("Please enter only alphanumeric characters for the field fieldtocheck");
            return (false);
        }
    }
}

I think the best option would be to feed "getfield" into the the "checkfield" as arguments but how would I do that?

Any help appreciated.

2
  • 1
    What do you mean you want to turn it into an array? An array of what? Commented Dec 12, 2012 at 0:42
  • I could have my wording wrong but I mean to turn the variable "checkString" so that is contains multiple values. I think thats an array yes? Commented Dec 12, 2012 at 0:46

1 Answer 1

2

I would make your function more generic and use a class to identify the fields:

function checkFields(className, regex) {
    var inputs = document.getElementsByClassName(className);

    for (var i = 0; i < inputs.length; i++) {
        if (!regex.match(inputs[i].value)) {
            return false;
        }
    }

    return true;
}

function validate() {
    if (!checkFields('alphanum', /^[A-Za-z\d]+$/)) {
        alert('Please enter only alphanumeric characters');
    }
}

And your HTML could look like this:

<input type="text" class="alphanum" />

A much simpler (and better, IMO) approach would be to use the jQuery validation plugin.

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

1 Comment

Hi Blender, thanks for this. This code is to go on a sharepoint site so adding classes to a field can be [with my experience] complicated. Especially form list form fields which is why we're using the fieldTitle function. Regardless I kinda see where your going so I'll have a play and see what I can come up with.

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.