question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Custom validators

See original GitHub issue

react-dropzone provides some simple validation out of the box like accept, minSize and maxSize but it lacks rejection reason (#257 and #319) so it’s impossible to react to this rejection without the duplicating the validations in the user’s component’s code.

I have been thinking about implementing some kind of custom validator functions that you could then compose. Each such validator function should have a generic API. Something like this:

import { validate, assertMaxFileSize, assertMinFileSize, asserFileType } from 'react-dropzone'

function onValidate(files) {
  const { acceptedFiles, rejectedFiles } = validate(assertMaxFileSize, assertMinFileSize, asserFileType)(files)
  return [ acceptedFiles, rejectedFiles ]
}

const MyDropZone = (props) => {
  return <Dropzone onValidate={onValidate} />
}

This would allow create custom validators and react to rejections appropriately in the UI.

Thoughts?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:5
  • Comments:20

github_iconTop GitHub Comments

15reactions
josephecombscommented, Nov 3, 2019

here’s some boilerplate I wrote to validate image dimensions in case anyone needs it:

const onDrop = (accepted, rejected) => {
  let errors = [];

  if (rejected.length > 0) {
    errors.push('Image is over 10 MB and is therefore rejected.');
  } else {
    if (accepted[0].type !== 'image/jpeg') {
      errors.push('This image is not a jpg and is therefore rejected.');
    } else {
      var acceptedImg = accepted[0];
      var image  = new Image();
      image.addEventListener('load', function () {
        if (image.width !== 2500) {
          errors.push('This image must be exactly 2500 pixels wide.');
        } else if (image.height !== 3000) {
          errors.push('This image must be exactly 3000 pixels wide.');
        }

        // display errors or do success thing
        if (errors.length > 0) {
          alert(errors.join(', '));
        } else {
          alert('client side validations passed');
        }
      }.bind(this));
      image.src = acceptedImg.preview;
    }
  }
};
8reactions
josephecombscommented, Oct 31, 2019

I’ve updated my answer using FileReader, sorry for some nastiness in here:

const onDrop = (acceptedFiles, rejected, dropZoneRef) => {
  acceptedFiles.forEach((acceptedImg) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const binaryUrl = e.target.result;
      let errors = [];

      if (acceptedImg.type !== 'image/jpeg') {
        errors.push('This image is not a jpg and is therefore rejected.');
      }
      if (acceptedImg.size > 10000000) {
        errors.push('This image is over 10MB and is therefore rejected.');
      }
      const image  = new Image();

      image.addEventListener('load', () => {
        if (image.width !== 2500) {
          errors.push('This image must be exactly 2500 pixels wide.');
        } else if (image.height !== 3000) {
          errors.push('This image must be exactly 3000 pixels tall.');
        }
        // display errors or do success thing
        if (errors.length > 0) {
          alert(errors.join('\n'));
          PubSub.publish('IMAGE_ATTACH_FAILURE', { src: image.src, acceptedImg: acceptedImg });
        } else {
          PubSub.publish('IMAGE_ATTACH_SUCCESS', { src: image.src, acceptedImg: acceptedImg });
        }
      });

      image.src = binaryUrl;
    };
    image = reader.readAsDataURL(acceptedImg);
  });
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

Angular Custom Form Validators: Complete Guide
a custom validator is a function that validates the value of a form field according to a business rule, such as form example...
Read more >
Validating form input - Angular
A cross-field validator is a custom validator that compares the values of different fields in a form and accepts or rejects them in...
Read more >
Custom Validators in Angular | Articles by thoughtram
Angular comes with a subset of built-in validators out of the box. We can apply them either declaratively as directives on elements in...
Read more >
The best way to implement custom validators - Angular inDepth
Learning best practices on how to build your custom validator in Angular by reverse engineering the built-in Angular validators.
Read more >
Custom Validators — FluentValidation documentation
There are several ways to create a custom, reusable validator. The recommended way is to make use of the Predicate Validator to write...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found