2014-09-12 49 views
0

我这里有一个的jsfiddle - http://jsfiddle.net/1Lo7ag21/6/检查空间表单验证

我有一个名字输入,我想

我试图通过检查一个来验证名称字段中的第一和第二个名字空间。

如何检查该字段包含一个空间,如果它不

$('button').click(function(e){ 

     e.preventDefault(); 

     var name = $('#name').val(); 

     if(name.length == 0 && name.indexOf(' ') === -1){ 
      alert('Add first and last name with a space'); 
     } 

    }) 
+1

你的条件解释为'如果名称是空的空间不是found'。看到问题了吗?您还可以编写2个验证规则,其中一个为空名称(第一个),另一个为所需空间(第二个)。 – 2014-09-12 23:08:18

回答

0

你可以做somethong这样显示警报:

var name = $('#name').val(); 
name =  name.replace(/^\s+|\s+$/g,"") ; // strip any leading or trailing spaces 
name = name.replace(/\s+/g," "); // remove multiple intermediate spaces 
if (!/(^[A-Za-z]\s[A-Za-z- ']$)/.test(name)) { // first and second names separated by a space, allow for hyphen and apostrophe 
    alert ("You must enter your first name and last name separated by a space"); 
} 
+0

丹尼斯,这看起来应该工作,但它不 - - http://jsfiddle.net/1Lo7ag21/20/ – duckhill 2014-09-13 07:00:16

0

您似乎已经接近明白了,但是你的情况有点偏离。

if(name.length == 0 && name.indexOf(' ') === -1){ 

你检查名称长度为 0(空字符串)不包含空格。你可能打算在这里使用||(或)。

if(name.length === 0 || name.indexOf(' ') === -1){ 

http://jsfiddle.net/1Lo7ag21/13/

+0

你可以在这里看到工作verson http://jsfiddle.net/1Lo7ag21/14/ – Danis 2014-09-12 23:12:01

+0

@Danis The您链接的版本似乎不起作用。它里面还有'&&'。如果输入的文字不包含空格,则不会发出提示。编辑:好吧,现在你只是修改你的链接,指向你自己的答案的解决方案。添加到你的答案,不是我的。 – mpen 2014-09-12 23:14:33