kibana/x-pack/plugins/ml/common/util/validators.ts
Melissa Alvarez a4340f0ece
[ML] DF Analytics: add ability to edit job for fields supported by API (#70489)
* wip: add edit action to dfanalytics table

* add update endpoint and edit flyout

* show success and error toasts. close flyout and refresh on success

* show permission message in edit action

* update types

* disable update button if mml not valid

* show error in toast, init values are config values

* fix undefined check for allow lazy start

* prevent update if mml is empty
2020-07-06 15:10:01 -04:00

83 lines
2.3 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { ALLOWED_DATA_UNITS } from '../constants/validation';
/**
* Provides a validator function for maximum allowed input length.
* @param maxLength Maximum length allowed.
*/
export function maxLengthValidator(
maxLength: number
): (value: string) => { maxLength: { requiredLength: number; actualLength: number } } | null {
return (value) =>
value && value.length > maxLength
? {
maxLength: {
requiredLength: maxLength,
actualLength: value.length,
},
}
: null;
}
/**
* Provides a validator function for checking against pattern.
* @param pattern
*/
export function patternValidator(
pattern: RegExp
): (value: string) => { pattern: { matchPattern: string } } | null {
return (value) =>
pattern.test(value)
? null
: {
pattern: {
matchPattern: pattern.toString(),
},
};
}
/**
* Composes multiple validators into a single function
* @param validators
*/
export function composeValidators(
...validators: Array<(value: any) => { [key: string]: any } | null>
): (value: any) => { [key: string]: any } | null {
return (value) => {
const validationResult = validators.reduce((acc, validator) => {
return {
...acc,
...(validator(value) || {}),
};
}, {});
return Object.keys(validationResult).length > 0 ? validationResult : null;
};
}
export function requiredValidator() {
return (value: any) => {
return value === '' || value === undefined || value === null ? { required: true } : null;
};
}
export type ValidationResult = object | null;
export type MemoryInputValidatorResult = { invalidUnits: { allowedUnits: string } } | null;
export function memoryInputValidator(allowedUnits = ALLOWED_DATA_UNITS) {
return (value: any) => {
if (typeof value !== 'string' || value === '') {
return null;
}
const regexp = new RegExp(`\\d+(${allowedUnits.join('|')})$`, 'i');
return regexp.test(value.trim())
? null
: { invalidUnits: { allowedUnits: allowedUnits.join(', ') } };
};
}