Reputation: 21893
I need to detect on focusout if an input field contains only spaces. ie 1 or more spaces only and not any other characters?
At the moment it only detects if it contains 1 space only
$("#myInput").on("focusout",function(){
if($(this).val() ==" "){
//do work
}
});
Upvotes: 0
Views: 2567
Reputation: 148120
Trim and compare length and check if length is zero.
$("#myInput").on("focusout",function(){
if($(this).val().length && $.trim($(this).val()).length === 0){
alert("string contains one or more spaces")
}
});
Upvotes: 0
Reputation: 3057
I would go for the trim option.
Trim the input value then check if it is empty.
if (!String.prototype.trim) {
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
}
Upvotes: 0