Textbox validation

Discussion in 'JavaScript' started by ljCharlie, Dec 8, 2006.

  1. #1
    I have a function in JavaScript that will check to see if the textbox is empty or contain spaces. If it is then popup an alert box. In this case I have two textboxes so far. Both uses the same function with textbox1.Attributes.Add("onBlur"...and so on added in the Page Load method. I'm using asp.net 2.0. Below is the full function code.

    function textRequired(field, textMessage) 
    {
    var invalid = " "; 
    
    if(field.value == "" || field.value.indexOf(invalid) > -1) 
    {
    alert(textMessage);
    tempfield = field;
    
    //set the focus back to the textbox if the user did not enter a name 
    setTimeout(
    "tempfield.focus();",0); 
    return false; 
    }
    
    }
    Code (markup):
    The problem I run into is that when the page is loaded, an alert box will constantly popup since the two textboxes are empty to start with. How do I resolve this issue?

    One other thing I was wondering about is, is there an event for tab? For example, there are onClick, onKeyUp, onKeyDown and so on, I like to know if there is an event for determining when the user uses his/her tab to move to the next textbox.
     
    ljCharlie, Dec 8, 2006 IP
  2. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #2
    
    <script language="javascript">
    function doCheck(str)
    {
    	if(str.value == "" || str.value.indexOf(" ") > -1) 
    	{
    		alert("Errors have occured");
    		str.focus();
    	}
    }
    </script>
    
    <form action="" method="post">
    Onblur example <br />
    Word : <input type="text" name="whatever" onblur="javascript: doCheck(this);"/>
    </form>
    
    Code (markup):
     
    krakjoe, Dec 8, 2006 IP