dwp / govuk-casa

Framework for creating simple GOVUK Collect-And-Submit-Applications
ISC License
34 stars 24 forks source link

Provide documentation for, and an example of, a Custom Validator #44

Closed kiddhustle closed 1 year ago

kiddhustle commented 2 years ago

Summary

An example of how to create a custom validator in the docs would be helpful. I am not sure if the function signature for the validators has changed since v7.

For example I am not sure if these validators (used in an app using v7) will still work in v8 (current release):

https://github.com/dwp/ui-ds1500-frontend/blob/main/lib/validation-rules/ds1500.js

Proposed solution

Provide docs (describing function signature and parameters) and an example for custom validators.

Something like this:

class OneKiddHustle extends ValidatorFactory {
    constructor () {
        super(...arguments);
        this.name = 'OneKiddHustle';
    }

    validate (fieldValue, validateContext = {}) {
        const {journeyContext, waypoint, fieldName} = validateContext
        let isValid

        const errorMsg = this.config.errorMsg || {
            summary: `Sorry only one Kidd Hustle is allowed in this app. Go away and change your name!`,
            field: fieldName
        }

        try {
            isValid = fieldValue !== 'Kidd Hustle'
        } catch (err) {
            isValid = false
        }

        return isValid ? [] : [ValidationError.make({errorMsg, validateContext})]
        }
}

Benefits

It would help reassure teams considering adopting CASA if they have documentation and examples of key functionality.

lhokktyn commented 2 years ago

Thanks for raising this @kiddhustle . Documentation is certainly one of those areas we could improve a lot, and as coincidence would have it, we've made a start already, including validation customisation among other things. We're also tidying up the JSDoc annotations so we can generate some useful API documentation from it (in addition to the TypeScript "soft typing"). Should hopefully have this wrapped up in the next few weeks.

lhokktyn commented 1 year ago

Bit late to update this issue, but the docs were updated to address this :)