/***************************************************************************
* Copyright (C) 2009 by Evgeniy Sokolov *
* [email protected] *
***************************************************************************/
/* $Id$ */
var Form = RegulatedForm.extend({
WRONG: 1,
MISSING: 2,
primitives: null,
errors: null,
labels: null,
required: true,
construct: function()
{
arguments.callee.$.construct.call(this);
this.primitives = {};
this.errors = {};
this.labels = {};
return this;
},
setRequired: function(required)
{
this.required = (required === true);
},
isRequired: function()
{
return this.required;
},
getErrors: function()
{
var errors = this.errors;
for (name in this.violated)
errors[name] = this.violated[name];
return errors;
},
add: function(primitive)
{
this.primitives[primitive.getName()] = primitive;
},
get: function(name)
{
return this.primitives[name];
},
drop: function(name)
{
delete this.primitives[name];
return this;
},
getPrimitiveList: function()
{
return this.primitives;
},
importForm: function(form)
{
this.errors = {};
this.violated = {};
for (primitiveName in this.primitives) {
this.importPrimitive(this.primitives[primitiveName], form);
}
if (!this.isRequired() && this.isEmpty())
this.errors = {};
},
importPrimitive: function(primitive, form)
{
return this.checkImportResult(
primitive,
primitive.importFromForm(form)
);
},
checkImportResult: function(primitive, result)
{
var name = primitive.getName();
if (null === result) {
if (primitive.isRequired())
this.errors[name] = this.MISSING;
} else if (true === result) {
delete this.errors[name];
} else
this.errors[name] = this.WRONG;
return this;
},
addMissingLabel: function(primitiveName, label)
{
return this.addErrorLabel(primitiveName, this.MISSING, label);
},
addWrongLabel: function(primitiveName, label)
{
return this.addErrorLabel(primitiveName, this.WRONG, label);
},
addErrorLabel: function(name, errorType, label)
{
if (
!this.get(name)
&& !this.getRule(name)
)
throw "knows nothing about '"+name+"'";
if (!this.labels[name])
this.labels[name] = {};
this.labels[name][errorType] = label;
return this;
},
getTextualErrorFor: function(name)
{
if (
this.violated[name]
&& this.labels[name]
&& this.labels[name][this.violated[name]]
)
return this.labels[name][this.violated[name]];
else if (
this.errors[name]
&& this.labels[name]
&& this.labels[name][this.errors[name]]
)
return this.labels[name][this.errors[name]];
else
return null;
},
isEmpty: function()
{
for (primitiveName in this.primitives) {
if (
this.primitives[primitiveName].getValue()
|| this.errors[primitiveName] != this.MISSING
)
return false;
}
return true;
}
});Add a code snippet to your website: www.paste.org