Skip to content

Instantly share code, notes, and snippets.

@basarat
Created October 18, 2019 06:19
Show Gist options
  • Save basarat/683c76f9c702d93de10d581f9794718b to your computer and use it in GitHub Desktop.
Save basarat/683c76f9c702d93de10d581f9794718b to your computer and use it in GitHub Desktop.
some validators to use with formstate
import { Validator, applyValidators } from 'formstate';
/** One of the easy to validate values */
export type SimpleValue = string | boolean | number | null | undefined;
/**
* - Whitespace strings / false / null / undefined are considered invalid
*/
export const required: Validator<SimpleValue> = (value) => {
const error = "Value Required";
if (value == null) {
return error;
}
if (typeof value === 'string' && !value.trim()) {
return error;
}
else if (value === false) {
return error;
}
return null;
}
export const email: Validator<string> = (value: string) => {
if (value == null || value == '') return null;
if (typeof value !== 'string') {
return "Email must be a string";
}
value = value.trim();
// Src : http://emailregex.com/
if (!/^(([^<>()\[\]\\.,;:\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,}))$/g.exec(value)) {
return "Not a valid email address";
}
return null;
}
export const minLength = (minValue: number): Validator<string> => {
return (value: string) => {
if (value == null || value == '') return null;
if (value.length < minValue) {
return 'Minimum length required is ' + minValue.toString();
}
return null;
}
}
export const maxLength = (maxValue: number): Validator<string> => {
return (value: string) => {
if (value == null || value == '') return null;
if (value.length > maxValue) {
return 'Maximum length allowed is ' + maxValue.toString();
}
return null;
}
}
export const exactLength = (length: number): Validator<string> => {
return (value: string) => {
if (value == null || value == '') return null;
if (value.length !== length) {
return 'Length must be ' + length.toString();
}
return null;
}
}
/**
* Allows you to customize the message for validators
*/
export function withMessage<T>(message: string, ...validators: Validator<T>[]): Validator<T> {
return (value: T) => applyValidators(value, validators).then(res => {
return res ? message : res
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment