Category Archives: RegularExpressionValidator

[RESOLVED] textbox only allow numeric values

Hi

How to restrict user to not enter any characters othar than numeric values

i have this textbox

<asp:TextBox ID="txtToPage" SkinID="textBoxSmall" runat="server" Style="width: 30px;"></asp:TextBox>

Use Regular expression validator like enter regular expression, [0-9]* for above condition. Select Textbox and add regular expression validator under Validation controls.

It will allow user to enter numeric value only if any, if you don't want it to be blank you can use Required Field Validator as well alongside.

You can use regular expression with regularexpresionvalidator as follow

http://onetidbit.wordpress.com/2008/01/25/14/


Or

you can use ajax filteredtextbox

http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/FilteredTextBox/FilteredTextBox.aspx


Hi


   Use something like this


        <asp:TextBox ID="TextBox1" runat="server" ValidationGroup="Submit"></asp:TextBox>

        <asp:RegularExpressionValidator ID="RegularExpressionValidator1"                                ControlToValidate="TextBox1"   ValidationExpression="^\d*"  runat="server" ErrorMessage="RegularExpressionValidator" ValidationGroup="Submit">        </asp:RegularExpressionValidator >

        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="btn_Click" ValidationGroup="Submit" />

<div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste"><asp:TextBox ID="TextBox1" runat="server" ValidationGroup="Submit"></asp:TextBox></div> <div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" ValidationExpression="^\d*" runat="server" ErrorMessage="RegularExpressionValidator" ValidationGroup="Submit"></div> <div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        </asp:RegularExpressionValidator ></div> <div style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;" id="_mcePaste">        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="btn_Click" ValidationGroup="Submit" /></div>



Mahesh


Hi

 i  tried some javascripts but  they are not working with both browsers firefox and iexplore

or i need regular expression which not allowed other than numeric values

(not for only alert  message it shld  restrict)

Use RegularExpressionValidator validator and add numeric value reated

refer below links for create reguarl expression

http://www.regular-expressions.info/examples.html

check this.

http://www.aspsnippets.com/Articles/TextBox-Validation-using-JavaScript.aspx

Try the live demo at end of article 

Please show your code.

hI

I tried this javascript

<script type="text/javascript">

        //Keys ASCII

        //A – Z, a - z 65 - 90
        //0 - 9    48 - 57

        //Num0 – Num9 96 - 105

        //Backspace8
        //    

        var isShift = false;

        function keyUP(keyCode) {

            if (keyCode == 16)

                isShift = false;

        }


        function isNumeric(keyCode) {

            if (keyCode == 16)

                isShift = true;
            return ((keyCode >= 48 && keyCode <= 57 || keyCode == 8 || keyCode == 46 || keyCode >= 37 && keyCode <= 40 ||

(keyCode >= 96 && keyCode <= 105)) && isShift == false);

        }

       
        
    </script>

its working in both firefox ,iexplore


[RESOLVED] Randomly generated filename with FileUpload Control

Hi all, I have a FileUpload control that currently uploads pics to the Photos folder on my server. What I would like to know is how would I give it a randomly generated filename when it gets uploaded? As I don't want duplicates later on down the line. Cheers. (Code below).

 

<h2>Step 2: Add Photos</h2>
<p>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:RegularExpressionValidator runat="server" ID="valUpTest" ControlToValidate="FileUpload1" ValidationGroup="up"
            ErrorMessage="Image Files Only (.jpg, .bmp, .png, .gif)"
            ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.jpeg|.JPEG|.bmp|.BMP|.png|.PNG)$" />
</p>
<p>
    <asp:Button ID="btnUpload" runat="server" Text="Upload"
        onclick="btnUpload_Click" CausesValidation="true" />
</p>

 

Code Behind:

protected void btnUpload_Click(object sender, EventArgs e)
        {
            string path = Server.MapPath("~/Images/Photos/") + FileUpload1.PostedFile.FileName.ToString();
            FileUpload1.SaveAs(path);
        }

how about using a guid as the filename:

string s = Guid.NewGuid.ToString("N") ;

A simple and easy way is to combine [filename]+year+day+mins+seconds. you will have to remove the / and :  so it will come out like  pic1-20111680015. This will make sure you never have duplicate names

 

Thanks guys using a combination of both of your techniques I have managed to do it (code is below if anyone should need this in the future).

 

protected void btnUpload_Click(object sender, EventArgs e)
        {
            string fileName = "pic" + DateTime.Now.ToString("yyyy/dd/mm/ss").Replace("/", "");

            string path = Server.MapPath("~/Images/Photos/");
            FileUpload1.SaveAs(path + fileName);
        }

 

[RESOLVED] Detect text file during uplaod

Hi,

on my website I have file uploading (only text files). How to detect correct file type? 

Reading first 8 bytes doesn't works here because there are text files.

Any ideas?

Did you try checking the extension?

string extenstion = Path.GetExtension(filename);
        if (extenstion != ".txt")
        {
        }

This approach is not safe.

Hi,

olo21

How to detect correct file type? 

There's several methods you can do to control the type of upload file.

One is to use validation controls, it can force the checking to be done on the client. Of course, it need the browser allow client side use of the validation controls.

Check:http://www.developer2blog.com/post/2011/02/07/File-Upload-Control-File-Type-Validation.aspx

Second is use server side code to check file type. This method allow the file upload to server, but before save the file, it will first check the type on server.

You can check:http://www.beansoftware.com/ASP.NET-FAQ/FileUpload-Validation.aspx

If you want to a more secure way. I suggest to use both client side and server side validation

Hope this can help you.

hi..

when uploading ,you wanto check the file extension means you have to use httpfileuploaded,try this link to know more aboout this function 

http://vbdotnetaddict.blogspot.com/2011/02/upload-image-or-file-into-database-in.html

Use RegularExpressionValidator and also in case use customValidator with serverside function to actually validate the text file...

Thanks.

All your solutions are good but there is one disadvantage: they work based on a file extension. Is any other way to detect text files?

Hi,

olo21

they work based on a file extension

If you do not want to check the extension. The way I can think out is to use the server code: FileUpload1.PostedFile.ContentType.

After text files post to server. Use above code to check the mine type(text/plain). But also notice that, if user changed the file extension manually. The mine type will not be correct as we expect. Seems that if I changed the txt to jpg or pdf, the mine type is correct. But like .doc or other extension. The type will changed also.

Hope this can help you.

Hi,

olo21

they work based on a file extension

If you do not want to check the extension. The way I can think out is to use the server code: FileUpload1.PostedFile.ContentType.

After text files post to server. Use above code to check the mine type(text/plain). But also notice that, if user changed the file extension manually. The mine type will not be correct as we expect. Seems that if I changed the txt to jpg or pdf, the mine type is correct. But like .doc or other extension. The type will changed also.

Hope this can help you.

[RESOLVED] GridView-required Field and regular expressions validator Issues...

Hi I have a website created in asp.net and have the following fields displayed in the grid view linked through a database.

  • <div> <div>

    First_Name   Last_name  City Username  Password Email Mobile Gender

    please let me how I can put validations when the edit button is clicked and the textboxs popout...

    I have tried a lot of ways like edit template and all but they have not been helpful

    Really need urgent help..If you need I can also post the code I am using..

    Thanking in advance..

    </div> </div>

The code I have written till now goes like this :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Grid View</title>
    
    
    
    <style type="text/css">
        #form1
        {
            height: 974px;
        }
        .style1
        {
        }
        #hidr
        {
            height: 23px;
            width: 51px;
        }
    </style>
</head>
<body style="text-align: center; background-color: #993366">
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" DataSourceID="SqlDataSource1" Height="356px"
        Width="360px" onselectedindexchanged="GridView1_SelectedIndexChanged"
        BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
        CellPadding="3" CellSpacing="2"
        onrowupdated="GridView1_RowUpdated">
        <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        <Columns>

            <asp:TemplateField ShowHeader="False">
                <EditItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
                        CommandName="Update" Text="Update"></asp:LinkButton>
                    &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
                        CommandName="Cancel" Text="Cancel"></asp:LinkButton>
                        <%--<asp:TextBox ID="TextBox13" runat="server" ></asp:TextBox>--%>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
                        CommandName="Edit" Text="Edit"></asp:LinkButton>
                    &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
                        CommandName="Delete" Text="Delete"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:BoundField DataField="First_Name" HeaderText="First_Name"
                SortExpression="First_Name" />
            <asp:BoundField DataField="Last_Name" HeaderText="Last_Name"
                SortExpression="Last_Name" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            <asp:BoundField DataField="Username" HeaderText="Username"
                SortExpression="Username" />
            <asp:BoundField DataField="Password" HeaderText="Password"
                SortExpression="Password" />
            <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
            <asp:BoundField DataField="Mobile" HeaderText="Mobile"
                SortExpression="Mobile" />
            <asp:BoundField DataField="Gender" HeaderText="Gender"
                SortExpression="Gender" />
        </Columns>
        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
        <EmptyDataTemplate>
            &nbsp;
        </EmptyDataTemplate>
        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
    </asp:GridView>
    <br />
    <asp:Button ID="Button" runat="server" onclick="Button_Click" Text="Insert" />
        <b>&nbsp;&nbsp;<asp:Button ID="Button1" runat="server"
        onclick="Button1_Click" Text="Go Back" />
    &nbsp;&nbsp; </b><asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        DeleteCommand="DELETE FROM [entered] WHERE [ID] = @ID"
        InsertCommand="INSERT INTO [entered] ([First_Name], [Last_Name], [City], [Username], [Password], [Email], [Mobile], [Gender]) VALUES (@First_Name, @Last_Name, @City, @Username, @Password, @Email, @Mobile, @Gender)"
        SelectCommand="SELECT * FROM [entered]"
        UpdateCommand="UPDATE [entered] SET [First_Name] = @First_Name, [Last_Name] = @Last_Name, [City] = @City, [Username] = @Username, [Password] = @Password, [Email] = @Email, [Mobile] = @Mobile, [Gender] = @Gender WHERE [ID] = @ID">
        <DeleteParameters>
            <asp:Parameter Name="ID" Type="Decimal" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="First_Name" Type="String" />
            <asp:Parameter Name="Last_Name" Type="String" />
            <asp:Parameter Name="City" Type="String" />
            <asp:Parameter Name="Username" Type="String" />
            <asp:Parameter Name="Password" Type="String" />
            <asp:Parameter Name="Email" Type="String" />
            <asp:Parameter Name="Mobile" Type="Decimal" />
            <asp:Parameter Name="Gender" Type="String" />
            <asp:Parameter Name="ID" Type="Decimal" />
        </UpdateParameters>
        <InsertParameters>
            <asp:Parameter Name="First_Name" Type="String" />
            <asp:Parameter Name="Last_Name" Type="String" />
            <asp:Parameter Name="City" Type="String" />
            <asp:Parameter Name="Username" Type="String" />
            <asp:Parameter Name="Password" Type="String" />
            <asp:Parameter Name="Email" Type="String" />
            <asp:Parameter Name="Mobile" Type="Decimal" />
            <asp:Parameter Name="Gender" Type="String" />
        </InsertParameters>
    </asp:SqlDataSource>
    <div id="inputForm" style="height: 543px" visible="true" runat="server">
      <br />
        Fi<b>rst Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span class="style1">
        <asp:TextBox ID="TextBox1" runat="server" MaxLength="30"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
            ControlToValidate="TextBox1" ErrorMessage="Required Field">Required Field</asp:RequiredFieldValidator>
        <br />
        <br />
        </span>
        <asp:Label ID="myLabel2" runat="server" Text="Last Name"></asp:Label>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span class="style1">
        <asp:TextBox ID="TextBox2" runat="server" MaxLength="20"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
            ControlToValidate="TextBox2" ErrorMessage="Required Field">Required Field</asp:RequiredFieldValidator>
        <br />
        <br />
        </span>
        <asp:Label ID="myLabel8" runat="server" Text="Username"></asp:Label>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span class="style1">
        <asp:TextBox ID="TextBox6" runat="server" MaxLength="15"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
            ControlToValidate="TextBox6" ErrorMessage="Required Field">Required Field</asp:RequiredFieldValidator>
        <br />
        <br />
        </span>
        <asp:Label ID="myLabel9" runat="server" Text="Password"></asp:Label>
        &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span class="style1">
        <asp:TextBox ID="TextBox9" runat="server" MaxLength="15"
            style="margin-top: 8px" TextMode="Password"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
            ControlToValidate="TextBox9" ErrorMessage="Required field">Required field</asp:RequiredFieldValidator>
        <br />
        <br />
        </span>
        <asp:Label ID="myLabel3" runat="server" Text="City"></asp:Label>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span class="style1">
        <asp:TextBox ID="TextBox3" runat="server" MaxLength="25"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
            ControlToValidate="TextBox3" ErrorMessage="Required Field">Required Field</asp:RequiredFieldValidator>
        <br />
        <br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        </span>
        <asp:Label ID="myLabel4" runat="server" Text="Email address"></asp:Label>
        &nbsp;&nbsp; <span class="style1">
        <asp:TextBox ID="TextBox4" runat="server" MaxLength="25"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
            ControlToValidate="TextBox4" ErrorMessage="Required Field">Required Field</asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1"
        runat="server" ErrorMessage="Invalid Email"
        
        
        
        
            ValidationExpression="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|co.in))$"
            ControlToValidate="TextBox4"></asp:RegularExpressionValidator>
        <br />
        <br />
        </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;
        <asp:Label ID="myLabel6" runat="server" Text="Mobile No."></asp:Label>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span class="style1">
        <asp:TextBox ID="TextBox5" runat="server" MaxLength="10"
            ontextchanged="TextBox5_TextChanged"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="TextBox5" ErrorMessage="Required Field">Required Field</asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="Validator1" runat="server"
            ControlToValidate="TextBox5" Text="Please enter only numbers"
            ValidationExpression="[0-9]{6,}"></asp:RegularExpressionValidator>
            
            <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" language="javascript">
        $(document).ready(function(){
    
    //called when key is pressed in textbox
    $("#TextBox5").keypress(function (e)  
    {
      //if the letter is not digit then display error and don't type anything
      if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
      {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
        alert("Only Nos are allowed");
        return false;
      }    
    });

  });
  </script>  
        <br />
        <br />
        <asp:Label ID="myLabel5" runat="server" style="text-align: left"
            Text="Choose Gender"></asp:Label>
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"
            Height="63px">
            <asp:ListItem Selected="True">Male</asp:ListItem>
            <asp:ListItem>Female</asp:ListItem>
        </asp:RadioButtonList>
        <br />
        <asp:Literal ID="litmsg" runat="server" Text="" Visible="false" />
        <br />
        <br />
        
        <asp:Button ID="myButton2" runat="server" Height="24px"
            onclick="myButton2_Click" Text="Create" />
        &nbsp;</b><span class="style1"></div>
    </form>
</body>
</html>

[RESOLVED] how to validate datetime

Hi All,

I want to enter date/time in the following format

22-02-2011  6:11:00 PM

So how can i validate this and user should be restricted to enter any other value

You could also use a RegularExpressionValidator.