我有一个非常有用的JavaScript代码:
<script type="text/javascript">
var maxWords = 100;
function limitLengthInWords(field)
{
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
if (wordCount >= maxWords)
{
field.value = value.match(re);
alert("Max reached");
}
document.getElementById(field).innerHTML = maxWords - wordCount;
}
</script>
我如何更换警报(“Max reach”),以便显示我正在检查的textarea的验证消息:
@Html.ValidationMessageFor(model => model.description)
我可以这样做:
<script type="text/javascript">
var maxWords = 100;
function limitLengthInWords(field)
{
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
if (wordCount >= maxWords)
{
field.value = value.match(re);
@Html.ValidationMessageFor(field,"Max reached");
}
document.getElementById(field).innerHTML = maxWords - wordCount;
}
</script>
答案 0 :(得分:0)
最简单的方法是显示一些隐藏的文字。
<span style="display:none;" class="max-reached">Max Reached</span>
$(".max-reached").show()
或者尝试使用执行此操作的库并包含倒计时。例如NobleCount
答案 1 :(得分:0)
确保您的模型正确注释,我使用密码属性作为示例
[StringLength(30, ErrorMessage = "Error Message")]
public string Password
{
get;
set;
}
更改此@ Html.ValidationMessageFor(字段,“Max reach”); 我假设$(字段)是id(例如$('#Password'),所有你需要做的就是访问mvc $(field).data('val-length')存储的数据信息