duplicatedName flag renamed on isUniqName
[arvados.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   onChange: (isValid: boolean | string) => void;
11   render: (hasError: boolean) => React.ReactElement<any>;
12   isRequired: boolean;
13   isUniqName?: boolean;
14 };
15
16 interface ValidatorState {
17   isLengthValid: boolean;
18 }
19
20 class Validator extends React.Component<ValidatorProps & WithStyles<CssRules>> {
21   state: ValidatorState = {
22     isLengthValid: true
23   };
24
25   componentWillReceiveProps(nextProps: ValidatorProps) {
26     const { value } = nextProps;
27
28     if (this.props.value !== value) {
29       this.setState({
30         isLengthValid: value.length < MAX_INPUT_LENGTH
31       }, () => this.onChange());
32     }
33   }
34
35   onChange() {
36     const { value, onChange, isRequired } = this.props;
37     const { isLengthValid } = this.state;
38     const isValid = value && isLengthValid && (isRequired || (!isRequired && value.length > 0));
39
40     onChange(isValid);
41   }
42
43   render() {
44     const { classes, isRequired, value, isUniqName } = this.props;
45     const { isLengthValid } = this.state;
46
47     return (
48       <span>
49         {this.props.render(!isLengthValid && (isRequired || (!isRequired && value.length > 0)))}
50         {!isLengthValid ? <span className={classes.formInputError}>This field should have max 255 characters.</span> : null}
51         {isUniqName ? <span className={classes.formInputError}>Project with this name already exists</span> : null}
52       </span>
53     );
54   }
55 }
56
57 const MAX_INPUT_LENGTH = 255;
58
59 type CssRules = "formInputError";
60
61 const styles: StyleRulesCallback<CssRules> = theme => ({
62   formInputError: {
63     color: "#ff0000",
64     marginLeft: "5px",
65     fontSize: "11px",
66   }
67 });
68
69 export default withStyles(styles)(Validator);