如果輸入字段僅包含空格,則需要在focusout上進行檢測。即只有一個或多個空格而不是其他任何字符?如何檢查輸入是否僅包含空格字符。即一個或多個空格而不包含其他字符
在它是否包含1個空間
$("#myInput").on("focusout",function(){
if($(this).val() ==" "){
//do work
}
});
如果輸入字段僅包含空格,則需要在focusout上進行檢測。即只有一個或多個空格而不是其他任何字符?如何檢查輸入是否僅包含空格字符。即一個或多個空格而不包含其他字符
在它是否包含1個空間
$("#myInput").on("focusout",function(){
if($(this).val() ==" "){
//do work
}
});
使用正則表達式:
if (/^\s+$/.test($(this).val())) { ...
。但效果很好。謝謝 – code511788465541441 2013-05-12 09:43:10
我真的希望SO編輯器有括號突出顯示。我一直這麼做。 – Barmar 2013-05-12 09:45:23
http://www.the-art-of-web.com/javascript/validate/ – 2014-09-12 11:46:07
修剪和比較長,並檢查是否長度爲零它只能檢測的時刻。
$("#myInput").on("focusout",function(){
if($(this).val().length && $.trim($(this).val()).length === 0){
alert("string contains one or more spaces")
}
});
如果字符串爲空,那麼這也不是真的嗎? – Barmar 2013-05-12 09:32:18
其不錯,但它也捕獲空字符串 – code511788465541441 2013-05-12 09:37:09
檢查我更新的答案,現在它會檢查字符串是否不是空字符串已經。缺少a) – Adil 2013-05-12 09:42:02
我會去修剪選項。
修剪輸入值,然後檢查它是否爲空。
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,' ');};
}
if (yourstring.match(/^\S+([\s\xA0]| )+/, '')){
作爲題外話:當心爲[限定空間(http://en.wikipedia.org/wiki/Space_(標點符號)#Spaces_in_Unicode)。 – Arjan 2013-05-12 09:29:29