我想检查在文本框中输入的两个或多个单词之间的间隔。如果有任何空间,那么我想提醒用户没有空间允许。我可以简单地使用“ if else”语句检查文本的存在。但是无法以这种方式完成所需的工作。我的代码如下:
<script type="text/javascript">
function checkForm()
{
var cName=document.getElementById("cName").value;
var cEmail=document.getElementById("cEmail").value;
if(cName.length<1)
{
alert("Please enter both informations");
return false;
}
if(cEmail.length<1)
{
alert("Please enter your email");
return false;
}
else
{
return true;
}
}
Name : <input type="text" id="cName" name="cName"/>
<br/>
<br/>
Email : <input type="text" id="cEmail" name="cEmail"/>
<br/>
<br/>
<input type="submit" value="Go!"/>
</form>
谢谢
最佳答案
只需使用字符串的match()
方法。例如:
'Spaces here'.match(' ');
那返回true。
'Nospace'.match(' ');
那返回false。
因此,对于您想要的东西,只需使用如下代码:
if(cName.match(' ')){
alert('Spaces found!');
return false;
}
Demo