Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
am developping an sample asp.net application i need to validate a textbox i used javascript to check whether the text box is empty or not.but its byepassing the validation if i enter a space only.how can i overcome it..........
Posted
Comments
walterhevedeich 1-Jul-11 0:46am    
Show us your validation code and probably the HTML tag for the textbox so we can somehow pinpoint where the culprit is.

If you want to count empty spaces also, check the length of the textbox's text. You can try below javascript code:
document.getElementById("txt").value.length

You can also try JQuery:
$("#txt").val().length


If you don't want to consider spaces then you need to trim the text before checking for length. To trim text in javascript you can use solution#2 and for JQuery you can do it like this:
$.trim($("#txt").val()).length


Here "txt" is the client-id of the textbox control.

Hope that helps!
 
Share this answer
 
v2
Hi,

asp.cs
C#
page_load(..)
{
  btnSubmit.Attributes.Add("onclick","return checkValidation();");
}

.aspx
C#
function checkValidation()
{
    var txt = trim(document.GetElementById('txtUser').value);
    if(txt.length == 0)
    {
       alert('Please fill in text box');
       return false;
    }  
    return true;
}
function trim(str)
{
    if(!str || typeof str != 'string')
        return null;
    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}
 
Share this answer
 
Comments
varunmohan 1-Jul-11 2:45am    
Thanks a lot..........
Sunasara Imdadhusen 1-Jul-11 3:02am    
you are welcome!!
C#
if(document.forms(0).textbox1.value == '')
            {
                alert('Please enter the text.');
                document.forms(0).textbox1.focus();
                return false;
            }
 
Share this answer
 
use requiredfieldvalidator(validation control in asp.net) i hope its solve your problem
 
Share this answer
 
v2
Comments
Rajneet Kaur 1-Jul-11 7:06am    
Add requiredfieldvalidator Control from Textbox , then go propeties of requiredfieldvalidator , select ControlToValidate ,there select text id of that textbox, to which u want to add requiredfieldvalidator also Type ERRor MEssage .....requiredfieldvalidator Control is to check, that textbox should not be blank.......
guptaadeepak 1-Jul-11 7:49am    
Rajneet you explain very well

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