GotKnowHow.com

How to Validate for Blank White Space in Text using Javascript

Simple javascript code to check for blank or empty space in a textbox.
by


Here's how you can do a simple validation check for blank spaces in javascript.   In the example below, the javascript function first trims the text value to make sure there is no extra white space and then checks the length for 0:

function validateBlankSpace(txtBoxId) {

                // Get the textbox by its Id
                var tb = document.getElementById(txtBoxId);
                // Trim white space and get text length
                var tbLen = tb.value.trim().length;
 
                // Check the text box for empty string (with no blank spaces)
                if (tbLen == 0)
                {
                    return confirm ('Are you sure you want this text box to be saved as empty?');  
                }
        }

Keep in mind, you may need to add/ or use different code in order to test for a null string/object.  The example above is testing for blank text inputs in a text box.

Hope this simple example gets you validating strings for blank spaces in javascript. 

--

For those of you who use ASP.NET / C#, the example below renders the "validateBlankSpace" function in the Page_PreRender and assigns the javascript function to the OnClientClick of the "SaveButton" when clicked:

    protected void Page_PreRender(object sender, EventArgs e)
    {

        // Gets a Text Box Client ID and checks to see if the textbox is empty (removes blank whites space before checking text lenght == 0)
        string script = @" 

        function validateBlankSpace(txtBoxId) { 

                // Get the subid textbox and its value
                var tb = document.getElementById(txtBoxId); 
                // Trim white space and get text length
                var tbLen = tb.value.trim().length;
 
                // Check the text box for empty string (with no blank spaces)
if (tbLen == 0) { return confirm ('Are you sure you want this text box to be saved as empty'); } } "; //register the client script, so that it is available during the first page render Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SaveAsValidation", script, true); //add the on client click event, which will validate the form fields on click the first time. SaveButton.OnClientClick = string.Format("return validateBlankSpace('{0}');", MyTextBox.ClientID); }

That's it!

 

 


0
0

Add your comment

by Anonymous - Already have an account? Login now!
Your Name:  

Comment:  
Enter the text you see in the image below
What do you see?
Can't read the image? View a new one.
Your comment will appear after being approved.


Did this article help you out, share it with your friends:

Ask a Question

140 characters left

Recent Articles