Availity / availity-reactstrap-validation

Easy to use React validation components compatible for reactstrap.
https://availity.github.io/availity-reactstrap-validation/
MIT License
191 stars 70 forks source link

maxLength not working properly for text input in Validation Custom Messages #174

Closed YannisMarios closed 4 years ago

YannisMarios commented 4 years ago

Hi,

In validations examples (https://availity.github.io/availity-reactstrap-validation/components/validators/),

In the Custom error Messages example you can see that maxLength is 16 chars for "nameCustomMessage" text input but it won't let you exceed 16 characters and so the error message never shows up.

Thanks

TheSharpieOne commented 4 years ago

While the browser will generally prevent user from entering more text than the maxlength attribute allows

https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/maxlength

This is outside of the control of this lib. The only thing I can suggest is to create a custom validation function that does not rely on the maxLength attribute. https://stackblitz.com/edit/reactstrap-validation-v2-vlwltp?file=Example.js

validate={{
  maxLength: value => {
    return !value || value.length <= 16 || 'This field is too long!';
  }
}}

You can easily make that reuseable by putting it in another file and importing it.

// customValidations.js
export maxLength = (length, message = 'This field is too long!') => value => {
  return !value || value.length <= length || message;
};

// where you need it
import { maxLength } from './customValidations';

//...
<AvField label="Enter Some Text" name="text" type="text" required validate={{
  maxLength: maxLength(16)
}} />
<AvField label="Enter Some Text" name="text" type="text" required validate={{
  maxLength: maxLength(24, 'Cannot be longer than 24 characters')
}} />
//...
YannisMarios commented 4 years ago

@TheSharpieOne This worked. Thank you