Simple form validation. Object-oriented.
Posted
by kalininew
on Stack Overflow
See other posts from Stack Overflow
or by kalininew
Published on 2010-04-07T08:31:00Z
Indexed on
2010/04/07
8:33 UTC
Read the original article
Hit count: 355
Problem statement: It is necessary for me to write a code, whether which before form sending will check all necessary fields are filled. If not all fields are filled, it is necessary to allocate with their red colour and not to send the form.
Now the code exists in such kind:
function formsubmit(formName, reqFieldArr){
var curForm = new formObj(formName, reqFieldArr);
if(curForm.valid)
curForm.send();
else
curForm.paint();
}
function formObj(formName, reqFieldArr){
var filledCount = 0;
var fieldArr = new Array();
for(i=reqFieldArr.length-1; i>=0; i--){
fieldArr[i] = new fieldObj(formName, reqFieldArr[i]);
if(fieldArr[i].filled == true)
filledCount++;
}
if(filledCount == fieldArr.length)
this.valid = true;
else
this.valid = false;
this.paint = function(){
for(i=fieldArr.length-1; i>=0; i--){
if(fieldArr[i].filled == false)
fieldArr[i].paintInRed();
else
fieldArr[i].unPaintInRed();
}
}
this.send = function(){
document.forms[formName].submit();
}
}
function fieldObj(formName, fName){
var curField = document.forms[formName].elements[fName];
if(curField.value != '')
this.filled = true;
else
this.filled = false;
this.paintInRed = function(){
curField.addClassName('red');
}
this.unPaintInRed = function(){
curField.removeClassName('red');
}
}
Function is caused in such a way:
<input type="button" onClick="formsubmit('orderform', ['name', 'post', 'payer', 'recipient', 'good'])" value="send" />
Now the code works. But I would like to add "dynamism" in it.
That it is necessary for me: to keep an initial code essentially, to add listening form fields (only necessary for filling).
For example, when the field is allocated by red colour and the user starts it to fill, it should become white.
As a matter of fact I need to add listening of events: onChange, blur for the blank fields of the form. As it to make within the limits of an initial code.
If all my code - full nonsense, let me know about it. As to me it to change using object-oriented the approach.
© Stack Overflow or respective owner