2

I currently have a validation script that has a selection of <input> elements stored in objects with properties such as "id", "type" "isRequired" and"isValid". I currently have this setup() function that does the following:

function setup(obj) {
    obj.getElement().onkeyup = function() {validate(obj)}
} 

In order to run this setup() function on all of my input objects I need to execute the following addEvents() function

function setEvents() {
    setup(firstName)
    setup(lastName)
    setup(email)
    setup(dateOfBirth)
}

I'm helping create a system that has multiple pages of nothing but forms so I'd prefer if I didn't have to type this for each object. Is there a way I can collect an array of all the objects that are based on a specific object template? This way I could loop through the array and apply a setup to each object in a single function. If not, are there alternatives?

(p.s. I've been asking so many object-oriented(oh, I crack myself up sometimes) questions lately because this is my first time messing with objects)

---Edit---

the object template I'm referring to looks something like this:

function input(id,isRequired,type) {
    this.id = id
    this.isRequired = isRequired
    this.type = type
}

this is then followed by a

firstName = new input('firstName',true,'alpha')
3
  • What do you mean by object template? You could directly create an array when you create those element objects. Commented Apr 25, 2011 at 22:38
  • @Felix check my edit so you'd suggest making the array when I initially create the firstName object? Commented Apr 25, 2011 at 22:47
  • updated my answer with a different solution to your problem. If you want something a little bit different, consider commenting and I might update it again. Commented Apr 25, 2011 at 23:21

4 Answers 4

1

As I said in my comment, you could add the element to an array when you create it:

var inputs = [];
var firstName = new input('firstName',true,'alpha');
inputs.push(firstName);

This is not ver convenient yet. But you could create another object which manages all this:

var InputManager = {
    elements: [],
    create: function(/* arguments here */) {
        var n = new input(/* arguments here */);
        this.elements.push(n);
        return n;
    },
    setup: function() {
        for(var i = this.elements.length; i--;) {
            (function(obj) {
                obj.getElement().onkeyup = function() {validate(obj)};
            }(this.elements[i]));
        }
    }
};

with which you can do:

var firstName = InputManager.create('firstName',true,'alpha');
// etc.
InputManager.setup();

Something along these lines. I think this would be a quite object oriented way. If you have a collection of objects, you often have another object which handles the functions that should be performed on all those objects.

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

3 Comments

btw I think you answered my question. I'm just reading up on how you did it. What type variable did you use for the InputManager? I'm not familiar with the statements you used to create what seems like methods for a function.
@Farren: This is object literal notation. E.g. var a = {} initializes a with an empty object. elements, create and setup are properties of the object (in my code). As functions are first class objects, you can assign them like any other value. You could also do: var a = {}; a.setup = function(){}; instead of var a = {setup: function(){} } (which is similar to the onkeyup assignment you did). It is just a more comprehensive way to write it.
Ok, I was just curious. I might use it in the future Thanks a ton!
1

As with most javascript questions, the easiest way to do this is with a library such as jQuery. If you have a unique way to differentiate these objects with a css selector (e.g., they all have the class "validate" or they're the only input[type="text"] fields on the page or something), then you can do a simple selection like $('.validate') to get an array of all these objects. You can get this array using javascript of course but it's a tad more complicated. Once you have the array you can loop over the elements or you can do a simple bind like $('.validate').change(validate); which will call the validate() method whenever a dom element with the class 'validate' changes.

Edit: So obviously I don't know the entirety of what you're trying to accomplish, but if you're new to web programming, just note also that no matter what you're doing on the client side (ie in the browser), all validation should also be done on the server side. Javascript validation is generally used to just be user-friendly and not to actually validate your inputs, since I could easily just turn javascript off or redefine validate as function validate() {} and bypass javascript validation for whatever reason.

2nd Edit: So I'm not sure if this answer was 100% what you're looking for but it's good to know regardless.

1 Comment

Thank you for your reply, I did want to avoid jQuery, and the solution wasn't really what I was looking for, but thank you for the tid-bit about the server-side scripting(which I don't currently deal with) I never thought about turning off the javascript to bypass the validation. ^Rep for the tip.
1

Judging by your examples you are not using jQuery. And for that reason alone, I'm going to up vote you. On the same note, after you get really comfortable with JS and how you can do things, really consider using a framework or saving your scripts so you don't have to reinvent the wheel for each project.

You can actually use the DOM to your advantage!

All the forms in your page can be referenced with document.forms[index]. Alternatively you can also reference a named form with document.formName.

Look at this jsfiddle for an example using the latter.

UPDATE

Reading your update and the fact that you needed a way of creating the input objects and setup the validation. I updated my fiddle with a different approach.

Used the id to hold the validation info regarding the element then the addValidation function reverts the id to it's basic form so you can still use it normally throughout your application.

The only requirement is that you addValidation the first thing after page load. So the ID get revamped first.

The solution is also JS safe, meaning if the user doesn't have JS, apart from no validation, no other things will happen.

2 Comments

Yes, I am trying to avoid jQuery, at least while I'm trying to learn javascript. I had an issue loading your jsfiddle, but your DOM reference comment did inspire me to rethink another part of my script. Thanks for the post!
@Farren... wooups, fixed the link. just type anything int he inputs to see the results.
-1

I think your problem is that the obj in the onkeyup scope is undefined.

function setup(obj) {
    //obj is desired
    obj.getElement().onkeyup = function() {validate(obj) //obj is undefined because onkeyup is the new scope of this function
}

instead you could do this:

function setup(obj) {
    obj.getElement().onkeyup = function() {validate(this) 
}

3 Comments

No. The anonymous function is a closure, it closes over obj.
and this inside the event handler refers to the DOM element and not the "input" object.
Just remember: A function has always access to the higher scopes.

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.