<input>字段的minlength属性似乎不起作用。

在HTML中是否有其他属性可以帮助我设置字段值的最小长度?


当前回答

我使用了最大值和最小值,这对我来说很有效,但我不确定这是否是一种编码方法。

<input type="text" maxlength="13" name ="idnumber" class="form-control"  minlength="13" required>

其他回答

现在HTML5规范中有一个minlength属性,以及有效性。tooShort接口。

现在所有现代浏览器的最新版本都启用了这两个功能。具体操作请参见https://caniuse.com/#search=minlength。

您可以使用pattern属性。还需要必需的属性,否则带有空值的输入字段将被排除在约束验证之外。

<input pattern=".{3,}"   required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">

如果你想创建一个选项来使用“空,或最小长度”的模式,你可以这样做:

<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}"   required title="Either 0 OR (8 chars minimum)">

我使用maxlength和minlength,无论是否需要,它对我来说都非常适合HTML5。

<输入id=“passcode”类型=“minlength”密码=“8”,maxlength=“10”>

`

minLength属性(不像maxLength)在HTML5中并不存在。但是,如果字段包含少于x个字符,则有一些方法可以验证字段。

一个使用jQuery的例子:http://docs.jquery.com/Plugins/Validation/Methods/minlength

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
        <script type="text/javascript">
            jQuery.validator.setDefaults({
                debug: true,
                success: "valid"
            });;
        </script>

        <script>
            $(document).ready(function(){
                $("#myform").validate({
                    rules: {
                        field: {
                            required: true,
                            minlength: 3
                        }
                    }
                });
            });
        </script>
    </head>

    <body>
        <form id="myform">
            <label for="field">Required, Minimum length 3: </label>
            <input class="left" id="field" name="field" />
            <br/>
            <input type="submit" value="Validate!" />
        </form>
    </body>

</html>

不是HTML5,但无论如何都很实用:如果你碰巧使用AngularJS,你可以在输入和文本区域都使用ng-minlength(或data-ng-minlength)。看看这个Plunk。