0

我有一个输入文本区域,我希望用户在其中输入他的全名。因此,必须在该字段中至少包含两个单词。

但验证代码与表单的操作代码 (action="nome.php") 冲突。

我该如何解决?

这是代码:

<script type="text/javascript">
// <![CDATA[
function validateMe(form_elm)
{
var full = form_elm.user.value;
// clear any spaces in front
while (full.charAt(0) == " ") full = full.substr(1);
// split and check for two names - dual purpose of also retrieving first and last name for future use
full = full.split(" ");
var first_name = full[0];
var last_name = full[1];
if (full.length < 2) alert("Please enter your full name.");
return false;
}
// ]]>
</script>

<form method="post" name="input" action="nome.php" onsubmit="return validateMe(this)">
Fazer reserva em nome de:
<input name="user" type="text"/>
<input type="submit" name="Submit" value="NEXT" />
</form>
4

1 回答 1

0

尝试从全名字段的值末尾修剪空格,然后将其拆分并检查数组的长度。

http://jsfiddle.net/bBZry/

function validate(el) {
    var text = el.user.value.trim();
    console.log(text);
    var words = text.split(" ");
    if (words.length > 1) {
     return true;   
    } else {
     return false;   
    }
}

if (!String.prototype.trim){
    String.prototype.trim = function(){
        return this.replace(/^\s+|\s+$/g,'');
    }
}
于 2013-08-02T19:03:50.900 回答