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
Doug
Updated July 16, 2010
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!