使用 HTML 模式和所需属性的解决方案
在下面的示例中,我们通过使用 <input> 元素上的模式和必需属性来设置值的最小长度。
如果未使用 required 属性,则具有空值的输入字段将从约束验证中排除。
title 属性用于允许在不符合模式时向用户显示消息。
如果未设置,将显示默认消息。
使用最小长度验证的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> input { border: 2px solid #000; } input:invalid:focus { background-image: linear-gradient(#34ebba, #6eeb34); } </style> </head> <body> <form action="/form/submit" method="post"> <input pattern=".{2,}" required title="至少2个字符"> <input pattern=".{5,8}" required title="5到8个字符"> </form> </body> </html>
如果我们想要一个选项来将模式用于空长度或者最小长度,请尝试以下示例。
设置最小长度验证的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> input { border: 2px solid #000; } input:invalid:focus { background-image: linear-gradient(#34ebba, #6eeb34); } </style> </head> <body> <form action="/form/submit" method="post"> <input pattern=".{0}|.{5,8}" required title="不填或者填写5到8个字符"> <input pattern=".{0}|.{6,}" required title="不填或者填写6个以上字符"> </form> </body> </html>
使用 HTML minlength 属性设置验证的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> input { border: 2px solid #cccccc; } input:invalid:focus { background-color: lightblue; } </style> </head> <body> <form action="/form/submit" method="post"> <label for="password">密码: <input type="password" name="password" id="password" required minlength="8"> </label> <input type="submit" value="提交"> </form> </body> </html>
在 HTML5 中,有一个 minlength 属性,但由于并非所有浏览器都支持它,如果支持,它可能会引起麻烦,我们建议另一种设置字段值的最小长度的方法。
无论如何,我们还将在最后演示带有此属性的示例。
日期:2020-06-02 22:15:12 来源:oir作者:oir