42a22e1c75baf40486175a19042be3e1363d6922
[arvados-workbench2.git] / src / utils / dialog-validator.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core';
7
8 type ValidatorProps = {
9     value: string,
10     render: (hasError: boolean) => React.ReactElement<any>;
11     isUniqName?: boolean;
12     validators: Array<(value: string) => string>;
13 };
14
15 class Validator extends React.Component<ValidatorProps & WithStyles<CssRules>> {
16     render() {
17         const { classes, value, isUniqName } = this.props;
18
19         return (
20             <span>
21                 {this.props.render(!this.isValid(value))}
22                 {isUniqName ? <span className={classes.formInputError}>Project with this name already exists</span> : null}
23                 {this.props.validators.map(validate => {
24                     const errorMsg = validate(value);
25                     return errorMsg ? <span className={classes.formInputError}>{errorMsg}</span> : null;
26                 })}
27             </span>
28         );
29     }
30
31     isValid(value: string) {
32         return this.props.validators.every(validate => validate(value).length === 0);
33     }
34 }
35
36 export const required = (value: string) => value.length > 0 ? "" : "This value is required";
37 export const maxLength = (max: number) => (value: string) => value.length <= max ? "" : `This field should have max ${max} characters.`;
38 export const isUniq = (getError: () => string) => (value: string) => getError() ? "Project with this name already exists" : "";
39
40 type CssRules = "formInputError";
41
42 const styles: StyleRulesCallback<CssRules> = theme => ({
43     formInputError: {
44         color: "#ff0000",
45         marginLeft: "5px",
46         fontSize: "11px",
47     }
48 });
49
50 export default withStyles(styles)(Validator);