Skip to content

Instantly share code, notes, and snippets.

@IlCallo
Created January 17, 2022 15:22
Show Gist options
  • Save IlCallo/5755b9b4a596590508561a705f5116a8 to your computer and use it in GitHub Desktop.
Save IlCallo/5755b9b4a596590508561a705f5116a8 to your computer and use it in GitHub Desktop.
Collection of validation rules for Quasar internal validation
import { isEmpty } from 'lodash-es';
import { useI18n } from 'src/boot/i18n';
const { t } = useI18n();
/**
* Validation rule which returns true if the value is considered "not empty",
* or an error message otherwise.
*/
export function required<T>(value: T) {
const message = t('common.validation.required');
if (value === undefined || value === null) {
return message;
}
// Booleans and BigInts are always valid
if (typeof value === 'bigint' || typeof value === 'boolean') {
return true;
}
// A number is valid unless it's NaN
if (typeof value === 'number') {
return !isNaN(value) || message;
}
// Check for empty string, array and objects
return !isEmpty(value) || message;
}
/**
* Validation rule which always returns true if the condition is not met,
* otherwise sends the value through the 'required' validation rule.
*/
export function requiredIf(conditionFn: () => boolean) {
return <T>(value: T) => !conditionFn() || required(value);
}
/**
* Validation rule which returns true if the value has length greater or equal to the provided value,
* or an error message otherwise.
*/
export function minLength(length: number) {
return <T extends { length: number }>(value: T) =>
value.length >= length || t('common.validation.minLength', { length });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment