To select the node/field in the dialog for validation, just add any validation attribute along with your value in the properties of that node. Then in the component field markup, you'll be able to see that data-attribute added.
For Ex: I have added the below validation attribute to my summary textfield
and the field markup of the dialog now looks like:
Now, this data-attribute will act as the selector for validating that particular field.
Use the below JS code snippet which you can put in clientlibs and add the categories as cq.authoring.dialog
(function ($window) {
$window.adaptTo("foundation-registry").register("foundation.validation.validator", {
selector: "[data-myapp-maxlength]",
validate: function(el) {
var maxlength = parseInt(el.getAttribute("data-myapp-maxlength"), 20);
if (isNaN(maxlength)) {return;}
var length = el.value.length;
if (length > maxlength) {
return "The field needs to be maximum " + maxlength + " characters.
It currently has a length of " + length + ".";
}
},
});
})($(window));
The dialog validation looks like this:
Here, based on the validation attribute added (data-myapp-maxlength=20) and the logic written in js, it will validate the field length and show the error if validation fails.
You can also add show() and clear() method for this foundation-validation by referring the below interface:
interface FoundationValidationValidator {
/**
* Only the element satisfying the selector will be validated.
*/
selector: string;
/**
* The actual validation function. It must return a string of error message
* if the element fails.
*/
validate: (element: Element) => string;
/**
* The function to show the error.
*/
show: (element: Element, message: string, ctx: FoundationValidationValidatorContext) => void;
/**
* The function to clear the error.
*/
clear: (element: Element, ctx: FoundationValidationValidatorContext) => void;
}
Reference: https://helpx.adobe.com/experience-manager/6-3/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/clientlibs/foundation/js/validation/index.html
No comments:
Post a Comment
If you have any doubts or questions, please let us know.