• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4304
  • Last Modified:

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

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
aditya_raj
Asked:
aditya_raj
  • 9
  • 8
  • 3
  • +4
1 Solution
 
Jeff CertainCommented:
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
 
aditya_rajAuthor Commented:
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
 
pavaneeshkumarCommented:
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
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
aditya_rajAuthor Commented:
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
 
anarki_jimbelCommented:
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
 
anarki_jimbelCommented:
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
 
aditya_rajAuthor Commented:
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
 
aditya_rajAuthor Commented:
Is ther anyway can i do that task using <asp:regularexpression > validator
0
 
Fernando SotoRetiredCommented:
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
 
Fernando SotoRetiredCommented:
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
 
Chandan_GowdaCommented:
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
 
Chandan_GowdaCommented:
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
 
Fernando SotoRetiredCommented:
@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
 
Fernando SotoRetiredCommented:
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
 
aditya_rajAuthor Commented:
Hi
Thanks for the reply. i want user id to accept a-z chars and A-Z chars also with 0-9,.,_ characters
0
 
Fernando SotoRetiredCommented:
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
 
aditya_rajAuthor Commented:
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
 
Fernando SotoRetiredCommented:
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
 
Chandan_GowdaCommented:
Yes I forgot to set the max length,Use the below Expression

"[\d._]{0,12}"
0
 
aditya_rajAuthor Commented:
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
 
Fernando SotoRetiredCommented:
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
 
aditya_rajAuthor Commented:
Thnaks for all suggessions.I got a new reglar expression which is working

It was [\.\w]+
0
 
Fernando SotoRetiredCommented:
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
 
Fernando SotoRetiredCommented:
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
 
Computer101Commented:
Forced accept.

Computer101
EE Admin
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 9
  • 8
  • 3
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now