Click here to Skip to main content
15,888,202 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to validate a textbox such that no one can enter characters in textbox. for that my javascript code is :
C#
function isSpaceKey(evt) {
          //   debugger;
            var charCode = (evt.which) ? evt.which : event.keyCode

            if ((charCode < 47 || charCode > 57) &&  charCode != 8) {
                alert("Enter Numeral Values only!");
                return false;
            }


            return true;
        }

it is working fine but i want that the first number should not be 0. How can i do it? Thanks.
Posted
Comments
Dholakiya Ankit 24-Jul-13 5:58am    
can u try evt.value.substring(0,1)!="0"

Use this Code

C#
function vald1(objThis) {
            if (!(/^(?:[1-9]\d*|0)$/.test(objThis.value))) {
                alert("First number should not be '0'.");
                return false;
            }
            else
                return true;
        }
 
Share this answer
 
There are many ways to do that.

Simplest in your case would be to check the length of the the text in the textbox. For length = 0 i.e first character, just don't allow 0 (key code 48) otherwise go with your normal validation. So change your code to:
JavaScript
function isSpaceKey(evt) {
    //   debugger;
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (document.getElementById("TextBoxID").value.length == 0) { //for first character
        if (charCode == 48) {
            alert("Enter Numeral Values only!");
            return false;
        }
    }
    else {
        if ((charCode < 47 || charCode > 57) && charCode != 8) {
            alert("Enter Numeral Values only!");
            return false;
        }
    }

    return true;
}


Hope that helps!

Edit - I misread the question before. Updated the answer as per your requirement.
 
Share this answer
 
v3
Comments
Ankur\m/ 24-Jul-13 6:16am    
Also do change the alert message accordingly (0 is a numeral value ;) ).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900