Image URL validation using Regular Expressions in ASP.Net

Last Reply 22 days ago By dharmendr

Posted 22 days ago

i want th user to enter a image url in the text box ..i want the validation of that..

You are viewing reply posted by: dharmendr 22 days ago.
Posted 22 days ago

Hi v@run,

Refer below code. Use RegularExpressions to validate the url.

HTML

<asp:TextBox runat="server" ID="txtImageUrl" Text="https://i.imgur.com/6LLBMoM.jpg" />
<asp:Button Text="Validate" runat="server" OnClick="Validate" />

C#

protected void Validate(object sender, EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(txtImageUrl.Text, @"(https?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))"))
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Url is invalid.')", true);
    }
    else
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Url is valid.')", true);
    }
}

VB.Net

Protected Sub Validate(ByVal sender As Object, ByVal e As EventArgs)
    If Not System.Text.RegularExpressions.Regex.IsMatch(txtImageUrl.Text, "(https?:\/\/[^ ]*\.(?:gif|png|jpg|jpeg))") Then
        ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('Url is invalid.')", True)
    Else
        ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('Url is valid.')", True)
    End If
End Sub

Output

https://i.imgur.com/6LLBMoM.jpg - Valid Url

https://i.imgur.com/6LLBMoM.aspx - Invalid url