我有一个名为“title”的输入框。
我希望用户只输入不超过35个单词。
<input name="title" id="title" class="event-name gui-input" placeholder="Title" type="text">
<script type="text/javascript">
/* <![CDATA[ */
jQuery(function(){
jQuery("#title").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter Title"
});
});
</script>
答案 0 :(得分:4)
使用JavaScript split
方法:
var content = $("input#title").val() //content is now the value of the text box
var words = content.trim().split(/\s+/); //words is an array of words, split by space
var num_words = words.length; //num_words is the number of words in the array
if(num_words>35){
//too many words
return false;
}
希望这会有所帮助,您可以根据验证情况调整此代码。
<强> JSFiddle 强>
单行解决方案,用于返回输入中的单词数:
var num_words = $("input#title").val().trim().split(/\s+/).length;
<强> JSFiddle 强>
答案 1 :(得分:1)
我修改了Ben提供的解决方案。 让用户知道剩下多少个单词。
脚本...
$("#title").keyup(function(){
var content = $("#title").val(); //content is now the value of the text box
var words = content.split(/\s+/); //words is an array of words, split by space
var num_words = words.length; //num_words is the number of words in the array
var max_limit=35;
if(num_words>max_limit){
alert("Exceeding the max limit");
var lastIndex = content.lastIndexOf(" ");
$("#title").val(content.substring(0, lastIndex));
$('#remainingChars').text('Limit Exceeding');
return false;
}
else
{
$('#remainingChars').text(max_limit+1-num_words +" words remaining");
}
});
表单字段..
<input name="title" type="text" id="title" size="100" />
<div id="remainingChars">Max limit is 35 words.</div>
答案 2 :(得分:0)
您可以在keyup
事件
35个字= 34个空格
答案 3 :(得分:-1)
只需在输入字段中使用最大长度。
<input name="title" id="title" class="event-name gui-input"
placeholder="Title" type="text" maxlength="35">