Add _regex validation operator (#5089)

Closes #2917
This commit is contained in:
Rijk van Zanten
2021-04-15 17:25:51 -04:00
committed by GitHub
parent 1382f5da2e
commit 1fb4db1fda
6 changed files with 28 additions and 6 deletions

View File

@@ -1,10 +1,10 @@
import { BaseException } from './base';
import { ValidationErrorItem } from 'joi';
import { FilterOperator } from '../types';
import { FilterOperator, ValidationOperator } from '../types';
type FailedValidationExtensions = {
field: string;
type: FilterOperator | 'required';
type: FilterOperator | ValidationOperator;
valid?: number | string | (number | string)[];
invalid?: number | string | (number | string)[];
substring?: string;
@@ -97,6 +97,11 @@ export class FailedValidationException extends BaseException {
extensions.type = 'required';
}
if (joiType.endsWith('.pattern.base')) {
extensions.type = 'regex';
extensions.invalid = error.context?.value;
}
super(error.message, 400, 'FAILED_VALIDATION', extensions);
}
}

View File

@@ -251,7 +251,7 @@ export class AuthorizationService {
if (action === 'create') {
for (const name of requiredColumns) {
permission.validation._and[1][name] = {
_required: true,
_submitted: true,
};
}
} else {

View File

@@ -38,3 +38,5 @@ export type FilterOperator =
| 'nnull'
| 'empty'
| 'nempty';
export type ValidationOperator = 'required' | 'regex';

View File

@@ -1,5 +1,5 @@
import { Filter } from '../types';
import BaseJoi, { AlternativesSchema, ObjectSchema, AnySchema } from 'joi';
import BaseJoi, { AnySchema } from 'joi';
const Joi: typeof BaseJoi = BaseJoi.extend({
type: 'string',
@@ -142,7 +142,11 @@ function getJoi(operator: string, value: any) {
return Joi.number().less(values[0]).greater(values[1]);
}
if (operator === '_required') {
return Joi.invalid(null).required();
if (operator === '_submitted') {
return Joi.required();
}
if (operator === '_regex') {
return Joi.string().regex(new RegExp(value));
}
}

View File

@@ -84,6 +84,7 @@ validationError:
nnull: Value can't be null
required: Value is required
unique: Value has to be unique
regex: Value doesn't have the correct format
all_access: All Access
no_access: No Access
use_custom: Use Custom

View File

@@ -67,6 +67,16 @@
| `_empty` | The value is empty (null or falsy) |
| `_nempty` | The value is not empty (null or falsy) |
The following operators are **only available in validation permissions**:
| Operator | Description |
| ----------------------- | ------------------------- |
| `_submitted` | Field has to be submitted |
| `_regex` <sup>[1]</sup> | Field has to match regex |
<sup>[1]</sup> JavaScript "flavor" regex. Save the regex without leading/trailing `/` character, and make sure to escape
backslashes.
## Relational
You can target related values by nesting field names. For example, if you have a relational