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 render: (hasError: boolean) => React.ReactElement<any>;
12 validators: Array<(value: string) => string>;
15 class Validator extends React.Component<ValidatorProps & WithStyles<CssRules>> {
17 const { classes, value, isUniqName } = this.props;
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;
31 isValid(value: string) {
32 return this.props.validators.every(validate => validate(value).length === 0);
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" : "";
40 type CssRules = "formInputError";
42 const styles: StyleRulesCallback<CssRules> = theme => ({
50 export default withStyles(styles)(Validator);