Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///constraints.ts
- interface IRule {
- rule: IRuleTypes;
- errorMessage: string;
- }
- type IRuleTypes = 'required' | ICustomFunction;
- type ICustomFunction = ((value: string) => boolean);
- type ICustomValue = string;
- function getConstraintFunction(constraint: IRuleTypes): ICustomFunction {
- switch (constraint) {
- case 'required': {
- return required;
- }
- default: {
- return constraint;
- }
- }
- }
- function required(value: ICustomValue): boolean {
- switch (typeof value) {
- case 'string':
- return (value as string).length > 0;
- }
- }
- function checkForErrors(value: string, constraints: IRule[]): string {
- for (const constraint of constraints) {
- if (!checkForError(value, constraint)) {
- return constraint.errorMessage;
- }
- }
- return undefined;
- }
- function checkForError(value: string, constraint: IRule): boolean {
- return getConstraintFunction(constraint.rule)(value);
- }
- export default checkForErrors;
- export { checkForErrors, IRule };
- /// USAGE
- // Imports
- const constraints: IRule[] = [
- {
- rule: 'required',
- errorMessage: 'Privaloma įvesti esama kilometražą.'
- },
- {
- rule: (value: string) => /^([0-9]+)$/.test(value),
- errorMessage: 'Kilometražas turi būti sveikasis skaičius.'
- },
- {
- rule: (value: string) => /^(0|[1-9][0-9]*)$/.test(value),
- errorMessage: 'Kilometražas negali prasidėti 0.'
- },
- {
- rule: (value: string) => value.length < 7,
- errorMessage: 'Kilometražas negali būti didesnis negu 999 999.'
- }
- ]
- class Something extends React.Component<> {
- //...
- private getErrorMessage(): string {
- return this.state.valueChanged ? checkForErrors(this.props.value, constraints) : undefined;
- }
- public hasError(): boolean {
- return this.getErrorMessage() !== undefined;
- }
- render() {
- //...
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement