Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add required validator to ajax AsyncFileUpload?

How to add client side required validator to asyncfileupload ,to enforce user to select file before submitting the page.

like image 241
user359634 Avatar asked Nov 20 '25 18:11

user359634


2 Answers

You could also set the text of a the hidden textbox in a server side method using C# or VB, rather than a client side Javascript or JQuery function.

    protected void afu_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        afu.SaveAs(Server.MapPath("Uploads\\") + e.FileName);

        txt.Text = e.FileName;       
    }
like image 72
John Meyer Avatar answered Nov 23 '25 11:11

John Meyer


I use a RequiredFieldValidator that validates an invisible TextBox. The TextBox is filled with an arbitrary text in the OnClientUploadComplete function. The only thing you cannot is setting the focus when it is validated. The example uses jQuery.

<ajaxToolkit:AsyncFileUpload runat="server" ID="afu" ClientIDMode="AutoID" UploaderStyle="Traditional" OnClientUploadComplete="asyncUploadComplete" OnClientUploadStarted="asyncUploadStarted" />
<asp:RequiredFieldValidator runat="server" ID="rfv" ControlToValidate="txt" Text="The file is required!" SetFocusOnError="false" />
<asp:TextBox runat="server" ID="txt" style="display:none" MaxLength="0" />
<script type="text/javascript">
    // AsyncFileUpload - OnClientUploadComplete
    function asyncUploadComplete(sender, args) {
        // Assemble info of uploaded file
        var contentType = args.get_contentType();
        var info = args.get_length() + " bytes";
        if (contentType.length > 0) {
            info += " - " + contentType;
        }
        info += " - " + args.get_fileName();
        // Put info in the first input field after the AsyncFileUpload control
        var source = $(sender.get_element());
        source.nextAll('input').val(info);
        // Validate immediately
        ValidatorEnable(source.nextAll('span')[0], true);
    }
    // AsyncFileUpload - OnClientUploadStarted
    function asyncUploadStarted(sender, args) {
        // Clear the first input field after the AsyncFileUpload control
        var source = $(sender.get_element());
        source.nextAll('input').val('');
    }
</script>
like image 45
arjan Avatar answered Nov 23 '25 11:11

arjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!