search

Home  >  Q&A  >  body text

Is it possible to use vuetify rules to validate image width, height?

I want to validate image width and height using vuetify. I wrote a function to check the image and compare it with a condition. Although I can check the width, height of the image, the rules are always wrong

<v-file-input 
                            :id="'file-input-' + label"
                            ref="fileInput"
                            :rules="rules.minResolution"
                            class="file-input-upload pt-0 pb-2"
                            prepend-icon=""
                            :error-messages="errorMessages"
                            @change="onChange"
                        >
                            <template #message="{ message }">
                                {{ showMessages($t(message), $t(label), maxSize) }}
                            </template>
                            <template v-if="imageError !== ''">
                                {{ $t(imageError) }}
                            </template>
                        </v-file-input>

This is the export function

export function minResolution(width, height, error) {
  return file => ( file && (new File(file, width, height) === true)) || error
}
function File(file, width , height) {
  const reader = new FileReader() 
  reader.readAsDataURL(file);
  reader.onload = evt => {
    const img = new Image();
    img.onload = () => {
      if (img.width >= width && img.height >= height) {
        alert(1)
        return true;
      }
    }
    img.src = evt.target.result;
  }
  return false;
}

Sorry my English is so poor

P粉652523980P粉652523980357 days ago574

reply all(1)I'll reply

  • P粉403804844

    P粉4038048442024-03-30 10:39:18

    I don't know if your minResolution can be async, but this is the only way, with async validation

    export async function minResolution(width, height, error) {
      return file => ( file && (await check_image_dimensions(file, width, height) === true)) || error
    }
    
    function check_image_dimensions(file, width , height) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      return new Promise(resolve => {
        reader.onload = evt => {
          const img = new Image();
          img.onload = () => {
            resolve(img.width >= width && img.height >= height);
          }
          img.src = evt.target.result;
        }
      });
    }
    

    reply
    0
  • Cancelreply