Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom errors in the computedValidation binding #232 #233

Merged
merged 1 commit into from
Feb 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading