0

我有一个运行良好的 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>

我如何替换警报(“达到最大值”),以便它显示我正在检查的文本区域的验证消息:

 @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>
4

2 回答 2

0

最简单的方法是显示一些隐藏的文本。

<span style="display:none;" class="max-reached">Max Reached</span>

$(".max-reached").show()

或者尝试使用执行此操作并包含倒计时的库。比如NobleCount

于 2013-09-12T15:41:39.657 回答
0

确保您的模型注释正确,我以密码属性为例

[StringLength(30, ErrorMessage = "Error Message")]
public string Password
{
    get;
    set;
}

改变这个@Html.ValidationMessageFor(field,"Max达到"); 我假设 $(field) 是 ID,例如 $('#Password') 你所要做的就是访问 mvc $(field).data('val-length') 存储的数据信息

于 2013-09-12T15:53:44.780 回答