Solved

restrict user entering white spaces in the textbox vb.net asp.net

Posted on 2007-11-26
29
3,844 Views
Last Modified: 2012-06-27
Hi,

I want to restrict the user not to enter any white spaces  while entering data to a text box and the size of the data should be 12.User can enter 0-9 digits or "." or "_" in the text.

Can anybody help me how to validate that text box.
0
Comment
Question by:aditya_raj
  • 9
  • 8
  • 3
  • +4
29 Comments
 
LVL 24

Expert Comment

by:Jeff Certain
Comment Utility
I'm assuming you want to do client-side validation since this is a web application. Since you're likely looking at credit card numbers, the format for those is somewhat well-known. Did you want to do a simple validation check on those as well?
0
 

Author Comment

by:aditya_raj
Comment Utility
I am not validating a credit card.I am validating a user name.Username can contain "." or "_" or "0-9" digits or "a-z" or "A-Z"
0
 
LVL 5

Expert Comment

by:pavaneeshkumar
Comment Utility
Set the MaxLength property of textbox to 12
check it for key down event for the text box and allow only those values which u wants to appear.
0
 

Author Comment

by:aditya_raj
Comment Utility
can i do that with regular expression validator.Because i am getting error in my javascript

function checkspaces()
    {
    var ele=document.getElementById ('txt_userid').value;
    if (isWhitespace(ele))
    {
    alert("Spaces are not allowed");
    }
    }

in code behind i added like
 txt_userid.Attributes.Add("OnKeyDown", "Javascript:checkspaces();")
When i run the app,it is breaking at this function.
0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
I believe the best way for validation is using regular expression. In ASP you can use then from JavaScript.
Or from serverside  - up to you.

You may use sample code like below.

The regex is simplified, it allows only characters you want but names like "--1--" are valid.
5 and 12 - min and max length for the name
        Dim ptn As String = "^\w{5,12}$"
 

        Dim s As String = txtEntry.Text
 

        Dim result As Boolean = Regex.IsMatch(s, ptn)

        MessageBox.Show(result)

Open in new window

0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
Sorry, the snippet was written in VB.

in C# it will be something like:


        string ptn = "^\w{5,12}$";

 

        String s = txtEntry.Text;

 

        bool result  = Regex.IsMatch(s, ptn);

        MessageBox.Show(result);

Open in new window

0
 

Author Comment

by:aditya_raj
Comment Utility
I need i vb.net.But above code will check for the spaces in a postback.I want it client side immediately after entering data.
0
 

Author Comment

by:aditya_raj
Comment Utility
Is ther anyway can i do that task using <asp:regularexpression > validator
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi aditya_raj;

Place a RegularExpressionValidator control where you want the error message to be displayed when the user enters invalid characters. The set the following properties of that control.

ControlToValidate = txt_userid    ' The name of the control select from drop down list
ErrorMessage       = Invalid length or characters if field
Text                      = Valid characters are 0 through 9 . and _ of length 12  ' Display
msg
ValidationExpression = [0-9\._]{12}     ' 12 characters from this list

Nothing else is needed. ASP.Net will create the client side script

Fernando
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi aditya_raj;

Sorry some type O's reposting;

Place a RegularExpressionValidator control where you want the error message to be displayed when the user enters invalid characters. Then set the following properties of that control.

ControlToValidate = txt_userid
ErrorMessage       = Invalid length or characters if field
Text                      = Valid characters are 0 through 9 . and _ of length 12  
ValidationExpression = [0-9\._]{12}

txt_userid in the above is the ID of the control to validate.
Nothing else is needed. ASP.Net will create the client side script

Fernando
0
 
LVL 7

Expert Comment

by:Chandan_Gowda
Comment Utility
Try the regularexpressionvalidator which is provide below it will allow only alphabets
<asp:regularexpressionvalidator id="rev" " runat="server" ErrorMessage="Please Enter Only Alphabets" ControlToValidate="txtBoxID" ValidationExpression="^[a-zA-Z]{1,30}$"></asp:regularexpressionvalidator>

Open in new window

0
 
LVL 7

Expert Comment

by:Chandan_Gowda
Comment Utility
You can try this one too this will allow . and _ along  numbers
<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ValidationExpression="[\d,.,_]*" ErrorMessage="YourMessage" ControlToValidate="txtBoxID"></asp:RegularExpressionValidator>

Open in new window

0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
@Chandan_Gowda;

This regular expression pattern, "[\d,.,_]*", will allow the characters "0-9" and "," and "_" and "." for a count of 0 up to any number characters. The characters that are valid are "0-9" and "." and "_" and the data needs to be of length of 12, if I understand the question correctly. Your pattern need to be something like "[\d._]{12}"

Fernando
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi aditya_raj;

This solution is the same as my last post except that the regex pattern is more refine.

Place a RegularExpressionValidator control where you want the error message to be displayed when the user enters invalid characters. Then set the following properties of that control.

ControlToValidate = txt_userid
ErrorMessage       = Invalid length or characters if field
Text                      = Valid characters are 0 through 9 . and _ of length 12  
ValidationExpression = ^[0-9\._]{12}$

The two extra characters in the pattern ^ and $ makes sure that it is the only text in the text box that match the pattern. So this is invalid "123.456.90_1Abc" but this is valid "123.456.90_1"

txt_userid in the above is the ID of the control to validate.
Nothing else is needed. ASP.Net will create the client side script

Fernando
0
 

Author Comment

by:aditya_raj
Comment Utility
Hi
Thanks for the reply. i want user id to accept a-z chars and A-Z chars also with 0-9,.,_ characters
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi aditya_raj;

Use this regex pattern.

^[\da-zA-Z\.,_]{12}$

Meaning of pattern

^        Start of string
\d       Any single digit
a-z     Any lower case character in the range of a-z
A-Z     Any upper case character in the range of A-Z
\.        The decimal point
,         The comma
_        The underscore character
{12}  Previous pattern must occurs 12 times
$        End of string
[ ]      Everything inside the [ ] is a character class and can match any one of the
          characters

Fernando
0
 

Author Comment

by:aditya_raj
Comment Utility
The above exp is not working.

I entered "test" as username there are no whitespaces in that still it is displaying the errormessage.

It is not compulsory that username is 12 chars.so i  used RegExp as ^[\da-zA-Z\.,_]$.

What can i do now.

examples of few usernames:
Tester
MDW.TNT
MD_Tnt

examples of not valid usernames:

MD  TNT
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi aditya_raj;

Your initial question stated a length of 12.

This pattern will except 1 or more character
^[0-9\._]+$   which is the same as this pattern, ^[0-9\._]{1,}$

If you want to set limits then this is how to modify the lower and upper limits.
^[0-9\._]{lower,upper}$

This will validate that the pattern is between 6 and 12 characters inclusive.
^[0-9\._]{6,12}$

Adjust the limits to what you need.

Fernando
0
 
LVL 7

Expert Comment

by:Chandan_Gowda
Comment Utility
Yes I forgot to set the max length,Use the below Expression

"[\d._]{0,12}"
0
 

Author Comment

by:aditya_raj
Comment Utility
Sorry i didn't understand.I have mentioned that i used  ^[\da-zA-Z\.,_]$.
which consists of  0-9 digits and a-z chars and A-Z chars and . and _.I don't want min and max lenghts.
Now what is the expression i need to use.

I have also tried ^[a-zA-Z0-9\.,_]$. But no Luck.Please reply me with the expression.

I am mentioning again i don't need to set  limits to my text. ok.
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
Comment Utility
As I have stated in a previous post the [ ] is a character class and any characters inside this class can be a match for the pattern for only one character in length.

Now because you are not placing a quantifier count after the closing ] in the character class you are indicating that you want to match one characters only.

Therefore a pattern such as "^[\da-zA-Z\.,_]$" will match a string of total length of 1 who's string character is a member of the character class. So to make this pattern work you need to tell the regex engine that it can have any number of characters in the string as long as the characters are in the character class.

This pattern,  "^[\da-zA-Z\.,_]*$" , tells the regex engine that the number of characters to match can be zero, the empty string, or and number of characters greater then zero.

If the pattern must have a least one character then this pattern will work, "^[\da-zA-Z\.,_]+$" .

if pattern must have a least X or more character then this pattern will work, "^[\da-zA-Z\.,_]{X,}$" , where X is the lower limit of the number of characters that the string must contain.

0
 

Author Comment

by:aditya_raj
Comment Utility
Thnaks for all suggessions.I got a new reglar expression which is working

It was [\.\w]+
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
I would like to see a resolution to this question seeming I have posted a working ASP .Net regex expression that will do what was needed and have tested it.

Thanks;
Fernando
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
I would like to see a resolution to this question seeming I have posted a working ASP .Net regex expression that will do what was needed and have tested it.

Thanks;
Fernando
0
 
LVL 1

Expert Comment

by:Computer101
Comment Utility
Forced accept.

Computer101
EE Admin
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
asp.net bundle 8 32
Binding a check box in an Asp.net DataGrid 4 26
Hide Tab Page 3 18
Problem to page 4 16
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now