Search code examples
reactjstypescriptvalidationtextfieldfluentui-react

Displaying multiple validations for FluentUI TextField component


Example Validations Display

So I'm converting an old Knockout blade to react, and I need to add multiple validations to a FluentUI TextField component. The example picture is what these validations should look like, but as of now, I have not been able to find an example of someone doing something similar with this component. I attached what I am currently using for the name field as that only requires one validation, but any help would be greatly appreciated. I am still relatively new to React/TypeScript so please bear that in mind.

const nameValidation = new RegExp("^$|^[A-Za-z][-A-Za-z0-9]{4,48}[A-Za-z0-9]$");

const validateAndGetError = (value:string): string =>  {
    return nameValidation.test(value) ? "" : ClientResources.Error.Message.validationEntityNameInvalid;
}
// the textfield is receiving the validate through onGetErrorMessage

<TextField styles={fieldStyles} placeholder={props.nameFieldPlaceholder} onGetErrorMessage={validateAndGetError} validateOnFocusOut onChange={(_, n) => setName(n)} />


Solution

  • Inside FluentUI Documentation you have an example for solution you are looking for. Focus is on section TextField error message variations:

    
    // Custom validation:
    const validation = (value: string) => {
      const x = 'Value must be Marko'
      const y = 'Put five characters'
      const errors = []
      if (value !== 'Marko' && value.length !== 5) {
        errors.push(x, y)
      } else if (value !== 'Marko' && value.length === 5) {
        errors.push(x)
      } else if (value === 'Marko' && value.length !== 5) {
        errors.push(y)
      } 
      return errors;
    }
    
    // Render list of errors:
    const getValidationErrors = (value: string) => 
    <Stack>
      {validation(value).map((x, i) =>
        <Stack key={i} verticalAlign="center" horizontal tokens={richErrorStackTokens}>
          <Icon iconName="Error" styles={richErrorIconStyles} />
          <Text variant="smallPlus">{x}</Text>
        </Stack>)}
    </Stack>
    
    <TextField
      label="Your name"
      defaultValue=""
      onGetErrorMessage={getValidationErrors}
    />
    

    Codepen working example.