The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. September 16, 2019, 09:20:21 PM

Login with username, password and session length


Pages: [1]
  Print  
Author Topic: Preliminary thoughts on a "form validator"  (Read 4479 times)
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« on: May 09, 2007, 03:08:31 AM »

I've been doing some "exploratory surgery" on javascript to see what i can "get away with"   Grin

I guess I'm just posting this here to help with the thought processes, so don't pay it too much attention. The code is petty much self-explanatory, I'm just testing the waters here to see what is possible in terms of creating "self validating" form inputs. Anyway, here it is;

Code:
<html>
<body>
<script language="javascript">

inp = document.createElement( 'input' );

inp.validate = function()
{
   if( this.testval != this.value )
     alert( "no match!" );

}

function function1()
{
   var bod = document.getElementById( 'body' );

   inp.setAttribute( 'type', 'text' );
   inp.setAttribute( 'value', 'foo' );
   inp.setAttribute( 'onClick', 'alert();' );
   inp.testval = 12;
   bod.appendChild( inp );
}

function function2()
{
  inp.validate();

}

function function3()
{
  inp2 = document.getElementById( 'existing' );
  inp2.testval = 12;
  inp2.validate = function()
  {
    if( this.testval != this.value )
      alert( "no match!" );

  }

}

function function4()
{
  inp2.validate();
}
 
</script>
<body id="body">
<button onclick="function1();">Append child</button>
<button onclick="function2();">Validate appended input</button>
<button onclick="function3();">Init existing</button>
<button onclick="function4();">Validate existing input</button>
<input type="text" name="existing">
</body>
</body>
</html>
Logged

"I want to be the guy my dog thinks I am."
 - Unknown
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #1 on: May 09, 2007, 09:58:35 AM »

Did that work?

I was thinking (per our convo) of more of a standalone class that you pass references to elements to, rather than appending the validation code right to the node... but if this works, then it'd be pretty clean looking to do something like...

<input id="editPhone" type="text" onChange="this.validate()">

// and later in script...

document.getElementById('editPhone').validate = function() { return validationClass.phoneNumber(); }

and the validationClass is a library of all the different types of validations you wanted to have, like phone numbers and such... that looks elegant, but I have no idea if that would work - particularly because I don't know that the browser would let you hang new props/methods on a DOM object... worth a test though...

but sheesh... looking back at all of that it'd be just as easy and perhaps more stable to just:

<input id="editPhone" type="text" onChange="return validationClass.phoneNumber()">

in which case I BELIEVE that returning a false would stop the change... can't remember right now...
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« Reply #2 on: May 09, 2007, 05:04:15 PM »

Did that work?

i don't post code that doesn't work unless I'm asking for help or I state explicitly it doesn't work, that would just be too misleading ;-)

I was thinking (per our convo) of more of a standalone class that you pass references to elements to, rather than appending the validation code right to the node... but if this works, then it'd be pretty clean looking to do something like...

<input id="editPhone" type="text" onChange="this.validate()">

// and later in script...

document.getElementById('editPhone').validate = function() { return validationClass.phoneNumber(); }

and the validationClass is a library of all the different types of validations you wanted to have, like phone numbers and such... that looks elegant, but I have no idea if that would work - particularly because I don't know that the browser would let you hang new props/methods on a DOM object... worth a test though...


That's what I was testing and I believe the OP demonstrates these at a very simple level. I haven't hit a dead end yet.


but sheesh... looking back at all of that it'd be just as easy and perhaps more stable to just:

<input id="editPhone" type="text" onChange="return validationClass.phoneNumber()">


I don't think that approach would be as reuseable/generic? Perhaps somewhere in the middle, a validationClass with form input objects that self validate based on rules attached to them at initialisation perhaps?

I figure we might as well design a reusable form validation class that we all can take advantage of......

Early days.......

Cheers,
td
Cheers,
td
Logged

"I want to be the guy my dog thinks I am."
 - Unknown
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #3 on: May 09, 2007, 05:54:37 PM »

I don't think that approach would be as reuseable/generic? Perhaps somewhere in the middle, a validationClass with form input objects that self validate based on rules attached to them at initialisation perhaps?

I figure we might as well design a reusable form validation class that we all can take advantage of......

I agree... but at some point your going to need to create the input - whether programmatically or in the HTML. So either you do the assignment at the HTML creation time or later in script by collecting the item by ID. It's a bit more than I can draft out right this second, but another way to do it would be to register the object with a class that places itself into the onChange callback of the text... for example,

validator = new validationClass();
validator.register('editPhone', 'phone');
validator.register('editFName', 'nonblank');
validator.register('editAge', 'nonblank,numeric,gte(1),lte(100)');
validator.register('editEMail', 'regex(/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z{2,4}/i)');
validator.register(editREMail', 'sameas(editEMail)');

... during the register function the element's onChange is vectored to the validatorClass so that it can check the element based on param 2 - which contains a comma-seperated list of ways we want the element checked. I am just blueskying here on what those validation notions would look like - but they would certainly be member functions of the class so that adding a new validation mechanism is as simple as adding the function to the base class then referencing it during the registration phase.

Thoughts?

/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« Reply #4 on: May 09, 2007, 07:47:50 PM »

Perk you are a mind reader, this is pretty much exactly where I was headed with this, in my mind I thought of something subtly different like this though;

validator.addElement( 'itemname' );
validator.addRule( 'itemname', 'trim' );
validator.addRule( 'itemname', 'notnull' );
validator.addRule( 'itemname', 'isalpha' );
validator.registerRule( 'some_new_rule', 'element > 1000' );
validator.addRule( 'itemname', 'some_new_rule' );

Along the lines of this but nowhere near as comprehensive (least not at this stage ;-) ) http:// pear.php.net/manual/en/package.html.html-quickform.php

We may not even need to catch the onchange, merely validate on submission? If we extrapolate the functionality of the validation engine we would have to provide a mechanism to specify what happens on validation failure, perhaps template based? Then we need to consider whether we would use a conventional POST for the form or consider using AJAX to get the form data back to the server and supply the appropriate response? What I like about using AJAX is that if the form submission failed for whatever reasons you could provide some level of redundancy such as drop back to a conventional post to an alternate location, etc.

Well, you did ask  ROFLMAO

Cheers,
td

[edit] This started as a discussion of a project for my kid's school but I think it's morphing into something way more than that. I can see lots of uses for this and in the biz some of us are in the redundancy of form submission is appealing. Rather than the user being lost if submission fails we could have levels of redundancy that go as far towards guaranteed delivery of data as possible including failure of our server (requires secondary server), failure of connection due to internet flakiness (router failures, etc.) and even complete failure of their internet connection, "I was unable to submit the form at this time would you like me to keep trying?" [/edit]
« Last Edit: May 09, 2007, 07:54:35 PM by thedarkness » Logged

"I want to be the guy my dog thinks I am."
 - Unknown
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #5 on: May 09, 2007, 08:20:43 PM »

test
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #6 on: May 09, 2007, 08:21:03 PM »

Hey TD -

When registering an object for validation, it would be much more efficient to do it all in one call rather than several - and in looking back at my code I also would have required parsing. Since there is no limit to the number of arguments you can pass on a JS function call, this would make sense:

validator.register('itemname', 'trim', 'notnull', 'isalpha');

In the function, the arguments reserved array holds all of what was passed - you can iterate with a simple for loop:
Code:
for (var i=0; i<arguments.length; i++) { doSomethingWith(arguments[i]); }

The only thing this does not address is when you want to do something more exotic, like register a regex to check against - you need to both instruct the obhect that you want to use a regex, and what the regex is - so this syntax needs to be rethunk.

Your code:
Code:
validator.registerRule( 'some_new_rule', 'element > 1000' );
validator.addRule( 'itemname', 'some_new_rule' );

creeps me out. This is because a parser and evaluator that is actually smart enough to make that sort of thing work, and yet is efficient enough to do things quickly will be quite an effort. I've written several languages in my day... so I have a reasonable amount of experience with that sort of thing. Since classes are easily extended, it would seem to me to simply add a new function prototype if you need something special - and have all the best and most used available on the class stock.

Along the lines of this but nowhere near as comprehensive (least not at this stage ;-) ) http:// pear.php.net/manual/en/package.html.html-quickform.php
That's some big mocassins to fill keemosabe...  Wink

We may not even need to catch the onchange, merely validate on submission? If we extrapolate the functionality of the validation engine we would have to provide a mechanism to specify what happens on validation failure, perhaps template based? Then we need to consider whether we would use a conventional POST for the form or consider using AJAX to get the form data back to the server and supply the appropriate response? What I like about using AJAX is that if the form submission failed for whatever reasons you could provide some level of redundancy such as drop back to a conventional post to an alternate location, etc.
In that case we would need another function to vector the onsubmit function of the form we were watching. This is pretty easy - we could:

Code:
validator.registerForm('formIDNotName');

and then in that function we set the onSubmit attribute to be <this> so that we can allow or disallow the submission.

That makes sense provided someone is always using forms for their work... I never do. I wrap things in a form only if I have to. When you start thinking AJAX you stop thinking forms and element names and start thinking visible divs and element IDs. No need for forms at all... in which case you'd need to either hook a button or let the coder hook it himself:

Code:
<input type="button" value="Do It" onClick="if (validator.goodToGo()) { document.formName.submit; }">

however that is largely inelegant.

Agree - this could morph into something rather cool and definitely usable...

/p
« Last Edit: May 09, 2007, 08:28:04 PM by perkiset » Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« Reply #7 on: May 09, 2007, 10:39:23 PM »

I'll start a separate thread in the javascript code section for my "Number Facts" project (kid's school). I think some fundamental developement of the validator class will mesh nicely with that. I've got some early mock-up code, I'll post it tonight and we can start throwing it out on the porch and see if the cat licks it up.

Cheers,
td
Logged

"I want to be the guy my dog thinks I am."
 - Unknown
thedarkness
Lifer
*****
Offline Offline

Posts: 585



View Profile
« Reply #8 on: May 09, 2007, 10:48:24 PM »

Interestingly anough this line;
   inp.setAttribute( 'onClick', 'alert();' );
in the initial post is the only code that does not work (located in function1() ) I guess I can see why it doesn't work but does anyone know the specifics of why it doesn't work.... hope that makes sense. It does not error, just fails silently.

Just curious, I don't need it at the mo.

Cheers,
td
Logged

"I want to be the guy my dog thinks I am."
 - Unknown
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #9 on: May 09, 2007, 11:46:39 PM »

That would work in firefox but not IE. Check out the table manager class in the Javascript Code Repository. Late in the class definition is a function called "attribute" - it shows the difference in how you'd attached that attribute in IE vs everything else lol.

Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
Pages: [1]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!