Help with controlling input to a textbox

Hello,

How do you force users to only enter letters, numbers the following two symbols "/", "-" and no blanks in a Textbox? and when the user clicks on the textbox how do you force the cursor to the far left?

Victor
vcharlesAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Luis PérezSoftware Architect in .NetCommented:
This type of restrictions work well in javascript, so I'll suggest a javascript solution for it.

For the 1st part of your question, you can create a javascript function like this:
        function restrictInput(e, notAllowedChars) {
            var keynum;
            var keychar;

            if (window.event) { // IE
                keynum = e.keyCode;
            } else { //Others
                keynum = e.which;
            }

            keychar = String.fromCharCode(keynum);
            return (notAllowedChars.indexOf(keychar) < 0);
        }

Open in new window


With this function you can use a string to set the not allowed chars on any input box. For example, the string '0123456789' to not allow numbers to be entered in the box.

To use it, it will depend on whether you're using an ASP.net textbox server control or a pure-html input text control.

If you're using ASP.net TextBox, you will need to add this line of code in Page_Load event:
VB code:
Me.YourTextBoxName.Attributes.Add("onkeydown","return restrictInput(event, 'notallowedchars')")

Open in new window

C# code:
this.YourTextBoxName.Attributes.Add("onkeydown","return restrictInput(event, 'notallowedchars')");

Open in new window


But if you use standard html input (input type="text"), you need to set the restriction directly in your input HTML definition:
<input type="text" id="myInput" onkeydown="return restrictInput(event, 'notallowedchars')" />

Open in new window


Now let's go with the second part of your question. As I assume that you're not using jQuery (if so it's much easier), you can create this function in your javascript:
        function setCaretPosition(elem, caretPos) {
            if (elem != null) {
                if (elem.createTextRange) {
                    var range = elem.createTextRange();
                    range.move('character', caretPos);
                    range.select();
                }
                else {
                    if (elem.selectionStart) {
                        elem.focus();
                        elem.setSelectionRange(caretPos, caretPos);
                    }
                    else
                        elem.focus();
                }
            }
        }

Open in new window


This function will position the caret into a text box in any position that you want (0 in this case). Again, applying of this function will depend on if your box is ASP.net TextBox or html input.

If ASP.net TextBox
VB code:
Me.YourTextBoxName.Attributes.Add("onclick","setCaretPosition(this, 0)")

Open in new window

C# code:
this.YourTextBoxName.Attributes.Add("onclick","setCaretPosition(this, 0)");

Open in new window


If HTML:
<input type="text" id="myInput" onclick="setCaretPosition(this, 0)" />

Open in new window


If you want the cursor to go to the left not only on box click, but also when box gains focus through pressing tab key, the change the "onclick" word to "onfocus". The "onfocus" option will work for both mouse and keyboard.

Hope that helps.
0
Luis PérezSoftware Architect in .NetCommented:
A last thing: reviewing your question I've seen that it would be better to change the behaviour of the restrictInput function to pass a parameter with the characters allowed better than the not allowed ones. If you prefer to use it that way, then change the parameter name from "notAllowedChars" to "allowedChars" and change the last line of code of the function from:
return (notAllowedChars.indexOf(keychar) < 0);

Open in new window

to
return (allowedChars.indexOf(keychar) >= 0);

Open in new window


Hope that helps.
0
vcharlesAuthor Commented:
Thank you for the code.
I am using ASP.NET controls with VB code. Looking at your code for the first part, based on your example with the numbers, does that mean I need to include all the symbols except for - and / and enter a space in the string? For example:
Me.Textbox1.Attributes.Add("onkeydown","return restrictInput(event, '-, /, ,')

Can I also force a user to enter two numbers a point and three numbers (xx.xxx)? and if they don't alert them immediately?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Luis PérezSoftware Architect in .NetCommented:
As I say in the second post, if you want to only allow letters, numbers and the "/" and "-" symbols, your string must be:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-'

But using the second form of the function, the one in which you set the allowed chars, not the not allowed chars.

Hope that helps.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vcharlesAuthor Commented:
Thanks, I guess that will automatically not allowed any space. I will test it and get back to you.
0
vcharlesAuthor Commented:
Hi again,

Just ran into a similar issue, I am using the code below to verify the format the data is entered in a textbox, problem is the users are allowed to enter multiple values in the same format, how do I modify the code to still verify the data is entered in the proper format?

Current code for single entry:
 Dim rx As New Regex("\d{2},\d{3}")
        If rx.IsMatch(TextBox1.Text) Then
            MsgBox("Format ok")
        else
       MsgBox("Format Not ok")
        End If

Issue is the users are allowed to also enter 99,999; 99,999, 99,999 etc..
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

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.