'IsNullOrWhitespace'在 JavaScript 中?
是否有相当于 .NET 的 String.IsNullOrWhitespace
以便我可以检查客户端的文本框是否包含任何可见文本?
我宁愿先在客户端执行此操作,而不是回发文本框值并仅依赖服务器端验证,尽管我也会这样做。
Is there a JavaScript equivalent to .NET's String.IsNullOrWhitespace
so that I can check if a textbox on the client-side has any visible text in it?
I'd rather do this on the client-side first than post back the textbox value and rely only on server-side validation, even though I will do that as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
对于简洁的现代跨浏览器实现,只需执行以下操作:
这是 jsFiddle。注释如下。
当前接受的答案可以简化为:
并利用虚假,甚至进一步:
trim() 在所有最新浏览器中都可用,因此我们可以选择删除正则表达式:
并添加混合中稍有虚假,产生最终(简化)版本:
For a succinct modern cross-browser implementation, just do:
Here's the jsFiddle. Notes below.
The currently accepted answer can be simplified to:
And leveraging falsiness, even further to:
trim() is available in all recent browsers, so we can optionally drop the regex:
And add a little more falsiness to the mix, yielding the final (simplified) version:
自己动手非常简单:
It's easy enough to roll your own:
不,但你可以写一个
no, but you could write one
尝试一下
检查字符串是否未定义、为 null、不是 typeof string、empty 或 space(s
您可以像这样使用它
Try this out
Checks the string if undefined, null, not typeof string, empty or space(s
You can use it like this
您必须编写自己的:
You must write your own:
trim()
是 JS 缺少的一个有用的字符串函数。添加它:
然后:
if (document.form.field.value.trim() == "")
trim()
is a useful string-function that JS is missing..Add it:
Then:
if (document.form.field.value.trim() == "")
提取两个最佳答案的相关部分,您会得到如下结果:
该答案的其余部分仅适用于那些对该答案与 Dexter 的答案之间的性能差异感兴趣的人。两者都会产生相同的结果,但此代码稍快一些。
在我的计算机上,对以下代码使用 QUnit 测试:
结果为:
Pulling the relevant parts of the two best answers, you get something like this:
The rest of this answer is only for those interested in the performance differences between this answer and Dexter's answer. Both will produce the same results, but this code is slightly faster.
On my computer, using a QUnit test over the following code:
The results were:
您可以使用正则表达式
/\S/
来测试字段是否为空格,并将其与空检查结合起来。例如:
You can use the regex
/\S/
to test if a field is whitespace, and combine that with a null check.Ex: