Permalink
Browse files

"maxLength" constraint applied when using "values.xxx" templating

The "maxLength" constraint is now applied to the value string
retrieved from the targeted field. The string is truncated with
continuation dots as needed to meet the constraint.

Other constraints are not enforced because it's hard to come up with
an automatic way of enforcing "minLength" or "pattern".
  • Loading branch information...
1 parent 68e08f4 commit 2f2caf4849ac0b3090bfc673cfce614884c807e9 François Daoust committed Jan 3, 2013
Showing with 19 additions and 6 deletions.
  1. +19 −6 lib/jsonform.js
View
@@ -1385,6 +1385,12 @@ var applyArrayPath = function (key, arrayPath) {
* The function handles values that contains template strings,
* e.g. {{values.foo[].bar}} or {{idx}}.
*
+ * When the form is a string, the function truncates the resulting string
+ * to meet a potential "maxLength" constraint defined in the schema, using
+ * "..." to mark the truncation. Note it does not validate the resulting
+ * string against other constraints (e.g. minLength, pattern) as it would
+ * be hard to come up with an automated course of action to "fix" the value.
+ *
* @function
* @param {Object} formObject The JSON Form object
* @param {String} key The generic key path (e.g. foo[].bar.baz[])
@@ -1428,6 +1434,7 @@ var getInitialValue = function (formObject, key, arrayPath, tpldata, usePrevious
return formElement;
};
var formElement = getFormElement(formObject.form || [], key);
+ var schemaElement = getSchemaKey(formObject.schema.properties, key);
if (usePreviousValues && formObject.value) {
// If values were previously submitted, use them directly if defined
@@ -1439,13 +1446,9 @@ var getInitialValue = function (formObject, key, arrayPath, tpldata, usePrevious
// the key as it may override the schema's default value
value = formElement['value'];
}
- else {
+ else if (schemaElement) {
// Simply extract the default value from the schema
- var schemaElement = getSchemaKey(
- formObject.schema.properties, key);
- if (schemaElement) {
- value = schemaElement['default'] || '';
- }
+ value = schemaElement['default'] || '';
}
if (value && value.indexOf('{{values.') !== -1) {
// This label wants to use the value of another input field.
@@ -1469,6 +1472,16 @@ var getInitialValue = function (formObject, key, arrayPath, tpldata, usePrevious
value = _.template(formElement.titleMap[value],
tpldata, valueTemplateSettings);
}
+
+ // Check maximum length of a string
+ if (value && _.isString(value) &&
+ schemaElement && schemaElement.maxLength) {
+ if (value.length > schemaElement.maxLength) {
+ // Truncate value to maximum length, adding continuation dots
+ value = value.substr(0, schemaElement.maxLength - 1) + '';
+ }
+ }
+
if (typeof value === 'undefined') return null;
else return value;
};

0 comments on commit 2f2caf4

Please sign in to comment.