Link to home
Start Free TrialLog in
Avatar of Victor  Charles
Victor CharlesFlag for United States of America

asked on

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
Avatar of Luis Pérez
Luis Pérez
Flag of Spain image

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.
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.
Avatar of Victor  Charles

ASKER

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?
ASKER CERTIFIED SOLUTION
Avatar of Luis Pérez
Luis Pérez
Flag of Spain 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
Thanks, I guess that will automatically not allowed any space. I will test it and get back to you.
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..