1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as React from 'react';
6 import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core';
8 type ValidatorProps = {
10 onChange: (isValid: boolean | string) => void;
11 render: (hasError: boolean) => React.ReactElement<any>;
16 interface ValidatorState {
17 isLengthValid: boolean;
20 class Validator extends React.Component<ValidatorProps & WithStyles<CssRules>> {
21 state: ValidatorState = {
25 componentWillReceiveProps(nextProps: ValidatorProps) {
26 const { value } = nextProps;
28 if (this.props.value !== value) {
30 isLengthValid: value.length < MAX_INPUT_LENGTH
31 }, () => this.onChange());
36 const { value, onChange, isRequired } = this.props;
37 const { isLengthValid } = this.state;
38 const isValid = value && isLengthValid && (isRequired || (!isRequired && value.length > 0));
44 const { classes, isRequired, value, isUniqName } = this.props;
45 const { isLengthValid } = this.state;
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}
57 const MAX_INPUT_LENGTH = 255;
59 type CssRules = "formInputError";
61 const styles: StyleRulesCallback<CssRules> = theme => ({
69 export default withStyles(styles)(Validator);