capval
Replaces the message a failed input validationInput validationRejecting bad input before it reaches the database. While this can be done manually inside a handler, there are solutions in place to derive type, range, enum and mandatory checks from the model definitions.SAP and community, unassessed annotation returns, and adds @validation.handler, which names a class that runs a check of the developer's own.
The default message for a failed @mandatory is Value is required, which in a multilevel form with many mandatory fields does not tell the user which field. @validation.message is annotated beside the standard annotations, such as @mandatory, @assert.format and @assert.range, and carries either the text or an i18n> key whose entry may hold {{Travel-EndDate}} placeholders that read values off the record under validation. @validation.handler points at a class extending BaseValidation and implementing isValid, which returns true or false; the class can read the field, its entity and a flat object of that entity and its parents up to the root, and capval works out the target and collates the errors. Those two annotations are what it introduces and there is no new constraint keyword: what a check may say is whatever isValid computes, and @mandatory and the @assert family remain @sap/cds@sap/cdsThe CAP Node.js runtime, which compiles the CDS model, serves the services declared in it, answers generic requests before any handler runs, and loads every cds-plugin.sap official, cap's.
Facts
Where it sits
Who is behind it
In the atlas: maintains 1, contributes to 1, wrote 2@MertSAPmaintainerMichaelSchmid-AGIContributes to this
In the atlas: contributes to 1@MichaelSchmid-AGI1 contributor
Before choosing this
Conditions
LicenceSAP Developer License Agreement 3.2 CAP§ 1, 2, 3A cds-plugin is used with SAP CAP materials, or an artifact is explicitly identified as a CAP plugin or application.
- § 1 License. Productive customer applications are limited to SAP BTP or another SAP-licensed platform, and mass extraction to a non-SAP product is restricted except where solely required for SAP interoperability.
- § 2 Intellectual Property. The agreement retains SAP's rights in the covered materials and limits making APIs, tools or software available to third parties, while preserving ownership of customer applications subject to SAP's underlying rights.
- § 3 Artificial Intelligence Training. The agreement prohibits use of the covered materials and customer applications for training artificial-intelligence models or systems.
What it declares
Every artifact
- Type
- CDS plugin
- Origin
- Independently maintained
- Runtime
- Node.js
As a CDS plugin
- Declared for
- >=8.0.0
- Distributed through
- npm
Connections
Rejecting bad input before it reaches a handler
Download
Install
npm add capvalDerived from the package name. No recipe recorded; the README has the configuration.
Learn more
- CAPVAL: A project is bornCAPVAL: A project is bornThis second CAPVAL post announces CAPVAL version 2.0, made compatible with CAP v8 after breaking changes there, with the fix shown as a custom cds.middlewares.after error handler. It restates the plugin's @validation.message annotation alongside standard annotations such as @mandatory as the input validation mechanic the project builds on, and the release otherwise adds automated tests and release-automation GitHub Actions rather than new annotations.published 2024-08-26MattBrightman, SAP Community
- Extend SAP Cloud Application Programming Model(CAP) Validations with the CAPVAL PluginExtend SAP Cloud Application Programming Model(CAP) Validations with the CAPVAL PluginThe complaint first: the built-in annotations are good for data integrity and poor at telling the user what went wrong, and there is no way to reuse a rule. capval, the plugin the post announces, adds @validation.message alongside the standard annotations rather than replacing them, and @validation.handler for a check written as a class. Published in January 2024, before the 1.2.0 line the README now pairs with @sap/cds 8.0.0 and above; the two annotations it shows are the two the README still documents.published 2024-01-09MattBrightman, SAP Community
README
quoted from MertSAP/CAPVAL under Apache-2.0, readExtend SAP Cloud Application Programming Model(CAP) Validations with the CAPVAL Plugin
SAP CAPVAL is a SAP Cloud Application Programming Model(CAP) plugin that aims to improve and extend the standard validations provided.
This plugin aims to address the following:
- Poor User Experience with default messages such as 'Value is required'. With a multilevel application with many mandatory fields this can leave the user feeling lost
- Large handlers for custom validations/messages to address the above
- Repetitive development implementing custom validations such as generating targets
Setup
To use CAPVAL, simply add the dependency to your project
For @sap/cds version less than 8.0.0 use CAPVAL version 1.1.0. Use CAPVAL version 1.2.0 and above for @sap/cds version 8.0.0 and above
npm add capval
Annotations
Custom Messages with contextual information
To override messages all we need to do is place the @validation.message annotation alongside existing input validation annotations(@mandatory,@assert.format,@assert.range...)
Examples
Custom Message
db/validations.cds
using { sap.fe.cap.travel as schema } from '../db/schema';
annotate schema.Travel {
@validation.message: 'Enter a valid begin date'
@mandatory
BeginDate;
}
Localisation
Localisation is supported and dynamic contextual information can be provided.
db/validations.cds
using { sap.fe.cap.travel as schema } from '../db/schema';
annotate schema.Travel {
@validation.message: 'i18n>begindate-error'
@mandatory
BeginDate;
}
_i18n/i18n.properties
begindate-error = Enter a valid begin date
Localisation with contextual information
db/validations.cds
using { sap.fe.cap.travel as schema } from '../db/schema';
annotate schema.Travel {
@validation.message: 'i18n>begindate-error'
@mandatory
BeginDate;
}
_i18n/i18n.properties
begindate-error = Begin Date required and must be before End Date {{Travel-EndDate}}
Custom Validations
The introduced annotation @validation.handler allows a class to be specified that implements a custom validation. This allows for modulisation and reuse of validations. Implementations must extend the BaseValidation class and implement the IsValid Method, returning true or false. CAPVAL will automatically determine the targets (in/to_Booking(BookingUUID etc etc), collate, and return the errors.
Example
Custom Validation
This handler checks that the begin date is before the end date
srv / handlers / BeginDateChecks.js;
const BaseValidation = require("capval");
module.exports = class BeginDateChecks extends BaseValidation {
isValid(InputValue) {
var travel = this.getNode();
if (travel.BeginDate > travel.EndDate) {
return false;
}
return true;
}
};
db/validations.cds
using { sap.fe.cap.travel as schema } from '../db/schema';
annotate schema.Travel {
@validation: {
message: 'Please enter a begin date that is before the end date',
handler: 'srv/handlers/BeginDateChecks.js'
}
BeginDate;
}
Advanced Scenario
A generic conditional validation with dynamic error messages
srv / handlers / ConditionalMandatoryCheck.js;
const BaseValidation = require("capval");
module.exports = class ConditionalMandatoryCheck extends BaseValidation {
isValid(InputValue) {
var data = this.getDataToRoot();
if (data["Travel-TravelStatus_code"] === "X") return true;
if (!InputValue) {
this.seti18nMessage(this.getField() + "-errorMessage");
return false;
}
return true;
}
};
db/validations.cds
using { sap.fe.cap.travel as schema } from '../db/schema';
annotate schema.Travel {
@validation: {
message: 'Default message',
handler: 'srv/handlers/ConditionalMandatoryCheck.js'
}
BeginDate;
@validation: {
message: 'Default message',
handler: 'srv/handlers/ConditionalMandatoryCheck.js'
}
EndDate;
}
_i18n/i18n.properties
BeginDate-errorMessage = Please enter a valid begin date
EndDate-errorMessage = Please enter a valid end date
Custom Data Scenario
Custom Variables, that are not part of the Business Object can be added to provide information in messages.
srv / handlers / BeginDateChecks.js;
const BaseValidation = require("capval");
module.exports = class BeginDateChecks extends BaseValidation {
isValid(InputValue) {
var travel = this.getNode();
var today = new Date().toISOString().slice(0, 10);
if (travel.BeginDate < today) {
this.seti18nMessage("begindatetoday-errorMessage");
this.setCustomMessageVariables({ today: today });
return false;
}
return true;
}
};
db/validations.cds
using { sap.fe.cap.travel as schema } from '../db/schema';
annotate schema.Travel {
@validation: {
message: 'Please enter a begin date that is before the end date',
handler: 'srv/handlers/BeginDateChecks.js'
}
BeginDate;
}
_i18n/i18n.properties
begindatetoday-errorMessage = Travel Begin Date {{Travel-BeginDate}} can not be before today {{custom-today}}
Methods
The following getter methods can be used to access information to assist with the validation:
- getField() : Returns the technical name of the Field getting validated. For Example: BeginDate
- getNode() : Returns the Entity Data for which the Field is member of. For example: The Travel Instance
- getMessage() : Returns the annotated error message
- getTarget() : Returns the calculated target
- getDataToRoot(): Returns a flat JSON Object(keys prefixed with the Entity Name-) of the Node under validation as well as its parents to root
- getData(): Returns the full data(root with all ancestors) of the instance
The following setter methods are available:
- setMessage(Message): Overwrites the Error Message. Variables in double curly brackets can be provided
- seti18nMessage(Message): Overwrites the Error Message by providing a key for an entry in the i18n.properties file
- setTarget(Target): Overwrites the generated field target
- setCustomMessageVariables(data): Allows a JSON Object with custom key value pairs to be used in error messages
Demo
SFLIGHT Scenario with CAPVAL https://github.com/MertSAP/cap-sflight
History
Notes
Fixes issues with nightly test suite that runs against latest dependencies
Suspect is was SAP/CDS 8.4.0
Swapped out jest with mocha
Notes
Fix for issue: Typo in node_modules/capval/cds-plugin.js which breaks work of custom handlers #15
Notes
A CAPVAL version compatible with SAP CAP v8
Other 2
Notes
Contextual Information Changes
- Changed the error handler(non draft scenarios) to use the body of the message rather than searching in the draft table which will always return no results
- Added a new test for contextual information
Other 4
Notes
Expanded Test Coverage and Defect Fixes
- Added additional tests to cover the testing of method this.seti18nMessage()
- Added additional tests to cover the testing of method this.setCustomMessageVariables()
- Fixed a defect where the error handler was overwriting the errors generating in on save
- Changed the test cases for drafts to use batch input as this simulates a fiori app and triggers the custom handler
Notes
Dependency updates
Others providing
Compare all 8 on the Input validation page →- abapDomCheckabapDomCheckChecks a structure's field values against ABAP domain fixed values and check tables outside the GUI, such as during a data import, answering with a rejected flag and the messages behind it.independent, abapChecks field values against domain fixed values and check tablesfrom ABAP
- com.sap.cds:cds-services-bomcom.sap.cds:cds-services-bomThe Maven bill of materials for CAP Java, pinning every com.sap.cds module in a release, from the API and core runtime to the Spring Boot starters and the CQN engine, to the same version.sap official, capMaven bill of materials pinning CAP Java module versionsfrom CAP
- cap-toolkitcap-toolkitA utility bundle for CAP handlers, with a chainable HandlerBuilder, role checks, validation rules and query helpers, collecting boilerplate that otherwise repeats across projects into one dependency.independent, capUtility bundle for CAP handlers: builder, roles, validation, queriesfrom CAP
- abap-data-validatorabap-data-validatorA validation library for ABAP that checks values such as dates, emails, URLs, JSON and GUIDs against type rules through one interface, or a whole internal table against a set of rules.independent, abapValidation library for ABAP checking dates, emails and GUIDsfrom ABAP
- sap-cap-validator-pluginsap-cap-validator-pluginA CAP plugin that checks incoming data against JSON Schema rules written as @Validator annotations on model elements, evaluated by Ajv, with no handler to register.independent, capCAP plugin validating input against @Validator JSON Schema rulesfrom CAP
- cds-validatecds-validateA package that runs Zod schemas as CAP validation middleware, so one schema replaces the hand-written checks at the top of a handler and failures come back as OData 422 errors per field.independent, capZod schemas as CAP validation middlewarefrom CAP
- @sap/cds@sap/cdsThe CAP Node.js runtime, which compiles the CDS model, serves the services declared in it, answers generic requests before any handler runs, and loads every cds-plugin.sap official, capCAP Node.js runtimefrom CAP
Details
Sources
Sources are graph entities: the same page may back several entries, and an unreachable source flags every row that rests on it.
Compatibility and provenance
Contributors
History in the atlas
- First seen.
For your agent
- Ref
artifact:mertsap-capval- JSON
- /artifacts/mertsap-capval.json
- MCP
- Connecting an agent