如果用户尝试在输入字段上输入的字符超过最大长度,该如何显示错误消息?

问题描述

用户尝试超过输入字段的最大长度时,如何向用户返回错误消息?

这是我在haml中使用的代码

= f.input :title,placeholder: 'Enter Title',:input_html => { :class => "form-control",autocomplete: :off,:maxlength => 255 }

在这里使用了maxlength,它工作正常,但是我想在输入字段下方显示一个错误,即“ 您已达到最大字符长度”。

有什么办法可以完成这项任务?

任何帮助将不胜感激。

解决方法

这是可以帮助您的基本代码

在您的application.js中

Apple  Strawberry
1      1             2
       0             2
0      1             1
,

您可以使用input触发或keyup JQUERY

$( document ).ready(function() {
   //make sure name attribute is the same
   $("input[name='title']").on('keyup',function() {
      if($(this).val().length > 255) {
        $(this).css({"color": "red"})
      }else{
        $(this).removeAttr( "style" )
      }
    });
});