Link to home
Create AccountLog in
Avatar of Epicmanagement
Epicmanagement

asked on

Place leading zeros before a number. VB.NET/ASP.NET

VB.NET, ASP.NET .NET 2.0

I have a textbox on the screen that accepts user input.  This textbox accepts a maximum of a 9 digit number.  The format is four digit year followed by any 5 numbers.

For example: 200783244

The user wants me to place leading zeros so that the number is always 9 digits long.  So If the user enters: 200788.  After the user tabs out, I need to change the number to: 200700088

The leading zeros need to come after the year and before the number.

I'd preffer this to be client side script, but if that's to hard I'll just do it server side.  Like after the user hits submit I'll just format it before it goes to the database.
Avatar of divinewind80
divinewind80

Are you already using Javascript?  If not, please use something like the following for server side:

Onclick event of submit button:
dim x as long
dim spacer as string
x = textbox1.text.length
if x <> 9 then
for y = 0 to 9 - textbox1.text.length
spacer = spacer & "0"
next
end if
textbox1.text = spacer & textbox1.text

This should give the desired results.  Let me know what you find.

Forgot to dim the y as long, also...
divinewind80:

That won't put the zeros after the year, as the poster requested.  That will always put them at the beginning of the string.

Try this:

TextBox1.Text = TextBox1.Text.Substring(0, 4) & TextBox1.Text.Substring(4).PadLeft(5, "0")
Here is a javascript solution for you.  Of course, just place this function in the HEAD inside some SCRIPT tags:

function padWithZeros(string) {
        var pad = '000000000'+ string;
        return pad.substring(pad.length - 9,pad.length);}

Then call the function like this:

<input type="text" onchange="this.value=padWithZeros(this.value);" />
ASKER CERTIFIED SOLUTION
Avatar of cheddar73
cheddar73

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Fair point about server-side vs client-side.
Epicmanagement,

I thought you wanted a client-side solution.  Did you change your mind?