Skip to content

Commit

Permalink
Support custom errors in the computedValidation binding #232
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisala committed Feb 19, 2024
1 parent 41a11bd commit a1af2a6
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion grails-app/assets/javascripts/forms-knockout-bindings.js
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,44 @@
return validationString;
};

/**
* Applies an attribute to the supplied element that controls the validation error displayed
* if a particular validation rule triggers
*/
function addJQueryValidationEngineErrorMessageForRule(rule, message, element){
// This comes from the private _validityProp method in the validation engine.
// The purpose of reproducing it here is to allow the correct error message attribute to
// be applied to the element
var validationEngineErrorMessageAttributeLookup = {
"required": "value-missing",
"custom": "custom-error",
"groupRequired": "value-missing",
"ajax": "custom-error",
"minSize": "range-underflow",
"maxSize": "range-overflow",
"min": "range-underflow",
"max": "range-overflow",
"past": "type-mismatch",
"future": "type-mismatch",
"dateRange": "type-mismatch",
"dateTimeRange": "type-mismatch",
"maxCheckbox": "range-overflow",
"minCheckbox": "range-underflow",
"equals": "pattern-mismatch",
"funcCall": "custom-error",
"funcCallRequired": "custom-error",
"creditCard": "pattern-mismatch",
"condRequired": "value-missing"
};

var errorAttribute = 'data-errormessage';
var errorAttributeSuffix = validationEngineErrorMessageAttributeLookup[rule];
if (errorAttributeSuffix) {
errorAttribute += '-' + errorAttributeSuffix;
}
$(element).attr(errorAttribute, message);
};

/**
* Adds or removes the jqueryValidationEngine validation attributes 'data-validation-engine' and 'data-errormessage'
* to/from the supplied element.
Expand Down Expand Up @@ -874,7 +912,13 @@
var modelItem = valueAccessor();

var validationAttributes = ko.pureComputed(function() {
return createValidationString(modelItem, viewModel);
var validationString = createValidationString(modelItem, viewModel);
_.each(modelItem || [], function(ruleConfig) {
if (ruleConfig.message) {
addJQueryValidationEngineErrorMessageForRule(ruleConfig.rule, ruleConfig.message, element);
}
});
return validationString;
});
validationAttributes.subscribe(function(value) {
updateJQueryValidationEngineAttributes(element, value);
Expand Down

0 comments on commit a1af2a6

Please sign in to comment.