Regular Expression to Control Input To Text Box

Dear All,

             I am new to all this regular expression I need a small help. I want to disable a certain character to be input into my text box such , > < # etc. So I want to control it via regular expression. How can I do it please ? Thanks.

0
subkir
8/7/2007 5:09:00 AM
asp.net.web-forms 93655 articles. 6 followers. Follow

9 Replies
510 Views

Similar Articles

[PageSpeed] 7

 Get yourself a copy of Expresso (a free download from http://www.ultrapico.com/Expresso.htm) This will allow you you write and test expression before using them in your program. Remember that all client side code such as a regular expression validator are a conveniance to the user and should not be relied on in a security sensitive situation.

For help on Regular Expressions look at http://www.ultrapico.com/Resources.htm


Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
0
TATWORTH
8/7/2007 5:56:30 AM

/[^<>#]*/ would match any string without < > & # in javascript.

but to include any ohter charecters like $ put backslash before them if they are reserved charecters for regular expression.

0
vogireddy
8/7/2007 6:16:01 AM

Dear Vogi,

              I tried to build a regular expression as below

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="txtUserName" Text="Invalid User Name" ValidationExpression="/[^<>#]*/" runat="server" ></asp:RegularExpressionValidator>. The problem is that it doesn work. Can you please me on this no enable thos characters to be allowed to be keyed into the username textbox. Thanks.

0
subkir
8/7/2007 4:37:38 PM

 A more secure method is to filter the user name server side. See my post at http://forums.asp.net/p/1104689/1696399.aspx#1696399 for a sample on how to do this. If your username is part of a logon form, security should outweigh the convenience of client side validation.

p.s. did you download Expresso and try out the regular expressio before putting it into your program? 


Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
0
TATWORTH
8/8/2007 5:31:06 AM

Dear Tatworth,

                    Yes I have downloaded expresso. So I choose alphanumeric. Then I get \W. From the expresso I selected Match Only If Absent for Alphanumeric. Below is my edited code

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="txtUserName" Text="Invalid User Name" ValidationExpression="\W" runat="server" ></asp:RegularExpressionValidator>. Every character I put in I get the error message. Can you please see what is wrong with my validation expression. Thanks.

 

0
subkir
8/8/2007 2:45:47 PM

It would be easier to make up a server side filter function. Jut what characters do you want to pass? Are your user names mapped to uppercase?

Do you want C# or VB.NET? 



Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
0
TATWORTH
8/8/2007 9:19:26 PM

Dear Tatworth,

                     Can you help me on that pleaese. Ok what I need is that just to limit the textbox to alphanumeric only. I want it to be in C# you help will be really appreciated thanks.

0
subkir
8/9/2007 4:59:18 PM

    private static string MODULE_NAME = "CommonData.cs";   
   #region " Filter constants "
    private const string FILTER_NUMERIC = "0123456789";
    private const string FILTER_DECIMAL = FILTER_NUMERIC + "-.";
    private const string FILTER_INTEGER = FILTER_NUMERIC + "-";
    private const string FILTER_LOWER = "abcdefghijklmnopqrstuvwxyz";
    private const string FILTER_POSTCODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
    private const string FILTER_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string FILTER_TELEPHONE = FILTER_LOWER + FILTER_INTEGER + " +()";
    private const string FILTER_TIME = FILTER_NUMERIC + ":";
    private const string FILTER_ALPHA = FILTER_LOWER + FILTER_UPPER;
    private const string FILTER_ALPHANUMERIC = FILTER_ALPHA + FILTER_NUMERIC;
    private const string FILTER_GENERAL_TEXT = FILTER_ALPHANUMERIC + " :/\\()-=+\n";
    #endregion
    #region " FilterAlphaNumeric "
    /// <summary>
    /// Filter AlphaNumeric (upper + lower + integer case) Values
    /// </summary>
    /// <param name="sIn">Input to filter</param>
    /// <returns>Filtered string</returns>
    public static string FilterAlphaNumeric(string sIn)
    {
      bool bDataDropped = false;
      return FilterWorker(sIn, FILTER_ALPHANUMERIC, ref bDataDropped);
    }
    /// <summary>
    /// Filter AlphaNumeric (upper + lower + integer case) Values
    /// </summary>
    /// <param name="sIn">Input to filter</param>
    /// <param name="bDataDropped">Set true if data is dropped</param>
    /// <returns>Filtered string</returns>
    public static string FilterAlphaNumeric(string sIn, ref bool bDataDropped)
    {
      return FilterWorker(sIn, FILTER_ALPHANUMERIC, ref bDataDropped);
    }
    #endregion
    #region " FilterWorker "
    /// <summary>
    /// Filter Worker
    /// </summary>
    /// <param name="sIn">Input to filter</param>
    /// <param name="sValid"></param>
    /// <param name="bDataDropped">Set true if data is dropped</param>
    /// <returns>Filtered string</returns>
    private static string FilterWorker(string sIn, string sValid, ref bool bDataDropped)
    {
      try
      {
        bDataDropped = false;
        if (sIn.Length == 0) return sIn;
        StringBuilder sOutput = new StringBuilder(sIn.Length);
        for (int iLoop = 0; iLoop < sIn.Length; iLoop++)
        {
          string sValue = sIn.Substring(iLoop, 1);
          if (sValid.IndexOf(sValue) >= 0) // sValue is valid!
            sOutput.Append(sValue);
          else
            bDataDropped = true;
        }
        return sOutput.ToString();
      }
      catch (Exception ex)
      { // System.Reflection.MethodInfo.GetCurrentMethod.Name
        string sMethod = "FilterWorker";
        CommonData.WriteEventError(MODULE_NAME, sMethod, ex, String.Empty);
        return sIn;
      }
    }
    #endregion

There are two functions - a basic filter and an overload to get feedback on when characters are dropped.

Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
0
TATWORTH
8/10/2007 4:41:27 PM

Try the following regular expression:

 ^\w+$

 This searches for any non-zero number of alphanumeric characters and only matches if it captures the entire string. Here is what the metacharacters mean:

^  =  Beginning of line or string
\w+ = Alphanumeric, one or more repetitions
$ =  End of line or string

 Regards,

 Jim

0
Jim
8/13/2007 2:03:25 AM
Reply:

Similar Artilces:

Load Text box of one web form with selected list item of list box of another web form
one help please Problem is i have two web forms  1.  ForiegnkeyTest.aspx  2. foroginkeytable.aspx   step 1 1 ForiegnkeyTest.aspx one web form <head runat="server"><script language="javascript" type="text/javascript">   function popWin()   {         var confirmWin = null;      confirmWin = window.open('foroginkeytable.aspx','anycontent',   'width=455,height=435,status');   }  </script> &...

VB .net Web Form will not get contents of Text Box
I have created a web form with text boxes that are bound to a DataSet/DataView.  I have created button to navigate up and down the recordset.  That all works fine. I need to have the ability to edit/add text in any of the boxes and then when clicking "Save" button, it would build an UPDATE query to send to the database. When the Save button is clicked, I have coded to DIM a string var (strSQL) to use to build the SQL command.  For some reason, it will only get the text from a text box if the data was pulled the database.  If I add/edit data, then the SQL command will ha...

control text in a text box inside a Form view
I want to get text from a querystring into a text box that is prt of a form view. I have tried writing code in the page load that changes the text value inside that text box but i get the error that the texbox name is not in the current context. My question is how to call a textbox (or any other control) inside a form view? You can use the FormView's OnDataBound event to access the textbox on your formview: OnDataBound="FormView1_OnDataBound" Protected Sub FormView1_OnDataBound(ByVal sender As Object, ByVal e As EventArgs)        If FormView1.Curren...

Controlling web control instances on Web Form
I have created a composite control, extending functionality of the Hidden Control. However, I would like to prevent the user from adding this control to the page multiple times. I only want one instance of the control on the Web Form. What setting in my project to I adjust to enable this functionality? I can not find it in any of the books that I have referenced. Is this a setting or is this code that has to be added to the inheriting class. Looks like there is no standard apporach. But I'd consider using static field to count number of created objects and throw exception if second object ...

Adding text box & check box to input ad form
Im trying to add a text box and check box  to the input ads form, but always get some kind of failure message.  Could someone please guide me to it or give me a explination on how it should be done. Thanks! Which files I sould be change and how, for expamle how add text box and check box  in  AppCode/BLL/Ads.cs file, code behind file or stored procedure. hi, If i am not wrong you are trying to dynamically adding a control to your page. But i could not get your point clearly. You mentioned that you wan to add the controls in  the file App_Code/BAL/Ads...

Enabling button after text changed on text box from form view control
I'm using form view to display some text box that contains user's personal info. There are "save" buttons for each text box which are disable as default. I want to enable them when text is changed on the the text box. I don't know how to write the the JavaScript function to do this task and i also don't know how to call the function from the the textbox control (onchange or ontextchange?). Here is the formview code: <asp:FormView ID="FormView1" runat="server" DataSourceID ="personalSQL"> <ItemTemplate > <ta...

Adding text box & check box to input ad form #2
Im trying to add a text box and check box  to the input ads form, but always get some kind of failure message. Could someone please guide me to it or give me a explination on how it should be done. Thanks! Which files I sould be change and how, for expamle how add text box and check box  in  AppCode/BLL/Ads.cs file, code behind file or stored procedure.     Take a look over here. http://forums.asp.net/t/1340067.aspx I just went through the addition process.The big diferences would be with the checkbox. In the first steps adding the column to the database, i...

Check if the text box "text" has changed (RePost from web forms forum)
Greetings! How can i know if the "text" inside of a text box has changed? For example, I currently have this: if (txtMU.TextChanged()) { } But this does not work. The other idea I had was to assign the existing value of the text box to a string and then when the user click the save button I can create a conditional statement to compare the original string with the new string. However, I would like something more effective as I have like 12 text boxes to compare. Thanks, EduardoThanks,Please Mark this post as answered if it was helpful. Here is the easiest way that I have ...

Need Regular Expression for Regular Expression Validator Control
Hi I am using a Regular Expression Validator Control to validate a text box. I want the textbox to only accept numbers, but I can't get the Regular Expression combination right. Any suggestions will be very much appreciated. E ValidationExpression="^\d$"Thanks, EdMicrosoft MVP - ASP/ASP.NET Thanks, This works, but it only accepts one digit no more. The expression i need should accept up to 8 digits and be an int. No decimal point!   Try ^\d{1,8}$. Good luck!Thank you,John M. Perry That's brilliant - thanks. How would I tweak that to make it accept d...

How to access a control on a web form from anoter web form
hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it possible to access lbl1 from form2, change its text permenantly? thanks.   refer: http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspxSSNPlease remember to click "Mark as Answer" on the post that helps you. MinaSamy: hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it p...

Ritch Text Box control from Free Text Box
I have a client that is complaintaning about how hurd it is to format a html page with that tool it is great for someone like us who knows how to work with HTML and all that.. is it a good program or tool that i can show him so he ca format a page for easily ?? right now is using Word and do a copy paste..but its not showing off the same thing... thanx.I like programming If he is using word you might want to look at this... Peters MHTML Control Cheers, Dave...

how to call controls of web control form in coding of other forms?
hello everyone i have one problem i have created one webcontrol shoppingcart in which there are two labels one of qty and other of amt which are initially enable =falsenow on other page(aspx page) i have one txtbox of qty as txtqty i want tat as soon as user enters qty txtqty and clicks on add cart button it shd be display d value in lblqty of web control shopping cart make sure i m using datalist on aspx page so give me suggestions on tat basis and my coding is in vb. plz give ur suggestions as fast as possible. Neeti what do you mean by webcontrol.... it this user control or normal ...

The performance in big form with about 70 controls(60 text box, 15 buttons, 5 combo box)
I have a big form with about 50 textbox or 5 combo box  and 15 command buttons, when I choose one item from a combo box, it need to get data from database and populate info. every time I click combo box it will refresh form and it's  very annoying.  Is it anyway to improve  performance? thanks  alot. I heard of AJAX, Does anybody have experience on it ? thanks. Summer06 AJAX may help you out with that. You can see home pretty cool examples and download the Atlas CTP from here. We've done some proof of concept work and it works really well for a scenario simi...

preserving the layout of text input via text input control
Ok what I want to do is, when using the text input control all cr, lf, crlf and spaces are preserved when the content is input in a db and that the information/layout is preserved when viewing it in a text input filed or grid control.any ideas   jim When you input text via a multiline textbox and insert it into a database your specified line breaks will be maintained. When retrieving the record, you will need to do a replace on the string in order to interpret these line breaks in your html:myField.Replace("\n", "<br />")Does this answer your q...

Web resources about - Regular Expression to Control Input To Text Box - asp.net.web-forms

Closed-form expression - Wikipedia, the free encyclopedia
In mathematics , an expression is said to be a closed-form expression if it can be expressed analytically in terms of a finite number of certain ...

Fighting abuse to protect freedom of expression
We believe that protection from abuse and harassment is a vital part of empowering people to freely express themselves on Twitter. Today, as ...

Joe Rogan's Facial Expression After Ronda Rousey Got Knocked Out Was Priceless - Bleacher Report
Joe Rogan 's face spoke for us all Saturday night. After UFC superstar Ronda Rousey got knocked out by a lethal kick from Holly Holm, the commentator ...

Jack Dorsey: 'Twitter stands for freedom of expression'
Newly-instated CEO Jack Dorsey laid out Twitter's commitment to open dialogue, in a keynote on stage at today's Twitter Flight developer conference ...

Make your technology a force for musical expression with this digital guitar
Computers, tablets, even iPhones have grown into powerful tools for music making, but for many who play guitar the bridge from analog instrument ...

Computers learn how to spot hidden facial expressions
Machines are good at spotting obvious emotions like smiles, but they're not so hot at detecting the extremely brief microexpressions that reveal ...

Turkey's YouTube Ban Violated Freedom Of Expression, European Court Rules
A YouTube ban in Turkey that lasted two years has now been ruled a violation of the European Convention on Human Rights. Back in 2008, a Turkish ...

Redbubble, A Profitable Channel For Artistic Expression
There is a growing movement of people who never want to follow a trend. Instead they embrace their own creative self-expression and are just ...

Smile!: Impressive Real-Time Facial Expression Transfer
This is a video from Stanford University of a system developed to transfer one person's facial expressions in real time to a live video feed ...

How Facial Recognition Uses Super-Simple Patterns to Understand Your Expression
Facial recognition systems use all kinds of clever software to work out who you are and even how you’re feeling. But in this video explainer, ...

Resources last updated: 1/4/2016 10:13:32 PM