Search results

Determine whether Uploader has File Input in React Uploader component

27 Oct 2021 / 3 minutes to read

By setting the required attribute to uploader input element, you can validate the input file that has any value in it. In the following sample, set required attribute to the uploader input element and showcase the validation failure message using the data-required-message attribute.

Copied to clipboard
import { createElement, detach, isNullOrUndefined, select } from '@syncfusion/ej2-base';
import { FormValidator } from '@syncfusion/ej2-inputs';
import { SelectedEventArgs, UploaderComponent } from '@syncfusion/ej2-react-inputs';
import {DialogComponent} from '@syncfusion/ej2-react-popups';
import * as React from 'react';
import * as ReactDOM from "react-dom";

export default class App extends React.Component<{}, {}> {
    public uploadObj: UploaderComponent;
    public dialogObj: DialogComponent;
    public path: object = {
        removeUrl: '',
        saveUrl: ''
    public content: string = 'Your details have been updated successfully, Thank you.';
    public width: string = '250px';
    public visible: boolean = false;
    public autoUpload: boolean = true;
    public header: string = 'Success';
    public extensions: string = '.png, .jpg, .jpeg';
    public options = { rules: { 'name': { required: [true, '* Enter your name'] } } };
    private customDropRef: HTMLElement;
    public onCreated(): void {
        this.uploadObj.dropArea = this.customDropRef;
        const formObj: FormValidator = new FormValidator('#form1', this.options);
        return formObj as any;
        setTimeout(() => {
            this.uploadObj.element.setAttribute('data-required-message', '* Choose your image to upload');
            this.uploadObj.element.setAttribute('required', '');
            this.uploadObj.element.setAttribute('data-msg-containerid', 'uploadError');
        }, 500);
    public browseClick(): void {
        const wrapperEle: HTMLElement = select('.e-file-select-wrap button', document) as HTMLElement;;

    public onFileSelect(args: SelectedEventArgs): void {
        if (args.filesData.length > 0) {
            if (document.getElementsByClassName('upload-image').length > 0) {
            const imageTag = createElement('IMG', { className: 'upload-image', attrs: { 'alt': 'Image' } });
            const wrapper: HTMLElement = createElement('span', { className: 'imgWrapper' }) as HTMLElement;
            const rootFile = this.customDropRef;
            rootFile.insertBefore(wrapper, rootFile.firstChild);
            this.readURL(wrapper, args.filesData[0]);
        args.cancel = true;

    public readURL (li: HTMLElement, args: any): void {
        const preview: HTMLImageElement = li.querySelector('.upload-image') as HTMLImageElement;
        const file: File = args.rawFile; const reader: FileReader = new FileReader();
        reader.addEventListener('load', () => { preview.src = reader.result as string; }, false);
        if (file) { reader.readAsDataURL(file); }
    public onFormSubmit(): void {
        const formObj: FormValidator = new FormValidator('#form1', this.options);
        const formStatus: boolean = formObj.validate();
        const imgValidate = !isNullOrUndefined(document.getElementsByClassName('imgWrapper')[0]);
        if (formStatus && imgValidate) {
            if(imgValidate) {
  public render(): JSX.Element {
    return (
        <div className="control_wrapper">
            <div className="col-lg-12 control-section">
                <h4 className="form-title">Photo Contest</h4>
            <div className="controls" id ="control_wrapper">
                <form id="form1" method="post" action=''>
                    <div id="name-attr" className="form-group" style={{paddingTop: '40px'}}>
                        <div className="e-float-input">
                            <input type="text" id="name" name="name" required={true} data-required-message='* Enter your name' data-msg-containerid="nameError"/>
                            <span className="e-float-line" />
                            <label className="e-float-text e-label-top" htmlFor='name'>Name</label>
                        <div id="nameError" />
                    <div id="dropArea">
                        <div id="uploadError" />
                        <div id='customBrowse' ref={dropEle => this.customDropRef = dropEle!} className="form-group dropUpload" onClick={this.browseClick=this.browseClick.bind(this)}>   Click here...
                         <UploaderComponent ref={uplaod => {this.uploadObj = uplaod !}} autoUpload={this.autoUpload} selected={this.onFileSelect = this.onFileSelect.bind(this)} allowedExtensions={this.extensions} created={this.onCreated = this.onCreated.bind(this)}/>
                    <div className="submitBtn">
                        <button type="button" className="submit-btn e-btn" id="submit-btn" onClick={this.onFormSubmit = this.onFormSubmit.bind(this)}>Submit</button>
                        <div className="desc"><span>*This button is not a submit type and the form submit handled from externally.</span></div>
                <DialogComponent id="dialog" width='350px' ref={dialog => {this.dialogObj = dialog !}} isModal={true} showCloseIcon={true} header={this.header} visible={false} content={this.content} target={".control_wrapper"} />

ReactDOM.render(<App />, document.getElementById('fileupload'));

You can also explore React File Upload feature tour page for its groundbreaking features. You can also explore our React File Upload example to understand how to browse the files which you want to upload to the server.