How to add the required validator to ajax AsyncFileUpload?

How to add the required client-side validation to asyncfileupload so that the user can select a file before submitting the page.

+3
source share
2 answers

You can also set the text of the hidden text field on the server side using C # or VB, and not on Javascript or JQuery on the client side.

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

        txt.Text = e.FileName;       
    }
+2
source

I am using RequiredFieldValidator, which checks for an invisible TextBox. A TextBox is filled with arbitrary text in the OnClientUploadComplete function. The only thing you cannot do is set the focus when it is checked. This 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>
+1

Source: https://habr.com/ru/post/1748722/


All Articles