hi
iam giving a value in text box as " 2010 - 1 " insted of 2010-1
it shows error,
please give me the code to avoid blank spaces within a string as given above,
iam using asp.net with vb.net
please help me.......

Dani AI

Generated

The sample input " 2010 - 1 " needs two things: normalize whitespace and remove spaces around the hyphen. 's Trim suggestion only removes leading/trailing spaces; it will not fix internal gaps. 's keypress idea can help while typing but is brittle (pastes, IMEs, mobile keyboards and accessibility can bypass it). The safest pattern is to sanitize on submit and always enforce on the server.

A compact VB.NET server-side normalization that handles the shown case uses Regex: remove spaces around hyphens, collapse repeated whitespace, then trim ends.

Imports System.Text.RegularExpressions

Dim raw As String = " 2010  -  1   "
raw = Regex.Replace(raw, "\s*-\s*", "-")   ' remove spaces around hyphen
raw = Regex.Replace(raw, "\s+", " ")       ' collapse runs of whitespace
raw = raw.Trim()
' result: "2010-1"

If the field must match a strict format (for example year-number like 2010-1), validate rather than only normalize. A simple server-side check:

Dim ok As Boolean = Regex.IsMatch(raw, "^\d{4}-\d+$")

Notes and troubleshooting: use \s in regex to catch tabs and NBSP characters, not just ASCII space. Avoid relying solely on keypress blocking; instead sanitize on oninput/onpaste if client-side feedback is needed, but always re-check on the server. Removing all spaces (Replace(" ", "")) is a blunt tool—only use it when spaces are never meaningful for that field. This approach ties back to the earlier tips from and while giving a robust, production-safe method.

Recommended Answers

All 3 Replies

>please give me the code to avoid blank spaces within a string as given above
>iam using asp.net with vb.net

Use JavaScript. Handle the keypress event of textbox.

eg,

...
  <head>
     <script type="text/javascript">
           function dothis() {
               var t=window.event.keyCode;
               if(t==32) // space
                   window.event.keyCode=0; 
          }
    </script>
  </head>
  ...
  ...
 <asp:TextBox id="TextBox1" Runat="server" onkeypress="dothis();" />

Hi..

I had same problem ..thanks for help me for giving me this code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.