@lion/form-core
Version:
Form-core contains all essential building blocks for creating form fields and fieldsets
143 lines (126 loc) • 3.01 kB
JavaScript
/* eslint-disable max-classes-per-file */
import { Validator } from '../Validator.js';
/**
* @param {?} value
*/
const isString = value => typeof value === 'string';
export class IsString extends Validator {
static get validatorName() {
return 'IsString';
}
/**
* @param {?} value
*/
// eslint-disable-next-line class-methods-use-this
execute(value) {
let hasError = false;
if (!isString(value)) {
hasError = true;
}
return hasError;
}
}
export class EqualsLength extends Validator {
static get validatorName() {
return 'EqualsLength';
}
/**
* @param {?} value
*/
execute(value, length = this.param) {
let hasError = false;
if (!isString(value) || value.length !== length) {
hasError = true;
}
return hasError;
}
}
export class MinLength extends Validator {
static get validatorName() {
return 'MinLength';
}
/**
* @param {?} value
*/
execute(value, min = this.param) {
let hasError = false;
if (!isString(value) || value.length < min) {
hasError = true;
}
return hasError;
}
}
export class MaxLength extends Validator {
static get validatorName() {
return 'MaxLength';
}
/**
* @param {?} value
*/
execute(value, max = this.param) {
let hasError = false;
if (!isString(value) || value.length > max) {
hasError = true;
}
return hasError;
}
}
export class MinMaxLength extends Validator {
static get validatorName() {
return 'MinMaxLength';
}
/**
* @param {?} value
*/
execute(value, { min = 0, max = 0 } = this.param) {
let hasError = false;
if (!isString(value) || value.length < min || value.length > max) {
hasError = true;
}
return hasError;
}
}
const isEmailRegex =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
export class IsEmail extends Validator {
static get validatorName() {
return 'IsEmail';
}
/**
* @param {?} value
*/
// eslint-disable-next-line class-methods-use-this
execute(value) {
let hasError = false;
if (!isString(value) || !isEmailRegex.test(value.toLowerCase())) {
hasError = true;
}
return hasError;
}
}
/**
* @param {?} value
* @param {RegExp} pattern
*/
const hasPattern = (value, pattern) => pattern.test(value);
export class Pattern extends Validator {
static get validatorName() {
return 'Pattern';
}
/**
* @param {?} value
*/
// eslint-disable-next-line class-methods-use-this
execute(value, pattern = this.param) {
if (!(pattern instanceof RegExp)) {
throw new Error(
'Psst... Pattern validator expects RegExp object as parameter e.g, new Pattern(/#LionRocks/) or new Pattern(RegExp("#LionRocks")',
);
}
let hasError = false;
if (!isString(value) || !hasPattern(value, pattern)) {
hasError = true;
}
return hasError;
}
}