Link to home
Start Free TrialLog in
Avatar of aditya_raj
aditya_raj

asked on

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.
Avatar of Jeff Certain
Jeff Certain
Flag of United States of America image

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?
Avatar of aditya_raj
aditya_raj

ASKER

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"
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.
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.
Avatar of Dmitry G
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

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

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.
Is ther anyway can i do that task using <asp:regularexpression > validator
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
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
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

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

@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
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
Hi
Thanks for the reply. i want user id to accept a-z chars and A-Z chars also with 0-9,.,_ characters
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
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
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
Yes I forgot to set the max length,Use the below Expression

"[\d._]{0,12}"
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.
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thnaks for all suggessions.I got a new reglar expression which is working

It was [\.\w]+
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
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
Forced accept.

Computer101
EE Admin