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>;
15 interface ValidatorState {
16 isPatternValid: boolean;
17 isLengthValid: boolean;
20 const nameRegEx = /^[a-zA-Z0-9-_ ]+$/;
21 const maxInputLength = 60;
23 class Validator extends React.Component<ValidatorProps & WithStyles<CssRules>> {
24 state: ValidatorState = {
29 componentWillReceiveProps(nextProps: ValidatorProps) {
30 const { value } = nextProps;
32 if (this.props.value !== value) {
34 isPatternValid: value.match(nameRegEx),
35 isLengthValid: value.length < maxInputLength
36 }, () => this.onChange());
41 const { value, onChange, isRequired } = this.props;
42 const { isPatternValid, isLengthValid } = this.state;
43 const isValid = value && isPatternValid && isLengthValid && (isRequired || (!isRequired && value.length > 0));
49 const { classes, isRequired, value } = this.props;
50 const { isPatternValid, isLengthValid } = this.state;
54 {this.props.render(!(isPatternValid && isLengthValid) && (isRequired || (!isRequired && value.length > 0)))}
55 {!isPatternValid && (isRequired || (!isRequired && value.length > 0)) ? <span className={classes.formInputError}>This field allow only alphanumeric characters, dashes, spaces and underscores.<br /></span> : null}
56 {!isLengthValid ? <span className={classes.formInputError}>This field should have max 60 characters.</span> : null}
62 type CssRules = "formInputError";
64 const styles: StyleRulesCallback<CssRules> = theme => ({
72 export default withStyles(styles)(Validator);