如何设置最小长度的输入



如何使用仅在定义了minlength时有效的oninput输入?

<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction()"><br><br>

如果我正确理解您的问题,那么您只想在满足minlength="8"时运行一些代码。

您可以使用validity对象检查输入是否正确验证。它包含所有验证标志的状态。看见https://developer.mozilla.org/en-US/docs/Web/API/ValidityState

<p id="demo"></p>

<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction(this)"><br><br>
<script>
function myFunction(el) {
// Check if input is tooShort
if (el.validity.tooShort) {
// You can just leave this empty
document.getElementById("demo").innerHTML = "Too Short"  
} else {
// Run this code if minlength is satisfied
document.getElementById("demo").innerHTML = el.value;
}
}
</script>


然而,您也可以像这样检查值的长度:

<p id="demo"></p>

<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction(this)"><br><br>
<script>
function myFunction(el) {
// Check if value is at least 8 characters....
if (el.value.length < 8) {
// You can just leave this empty
document.getElementById("demo").innerHTML = "Too Short"  
} else {
// Run this code if length is at least 8
document.getElementById("demo").innerHTML = el.value;
}
}
</script>

使用this.getAttribute方法读取属性值,然后相对调用函数

<input type="text" class="password2" id="password" name="password" minlength="8" oninput="this.getAttribute('minlength') !== undefined ? myFunction() : null">

您可以尝试以下操作:html:<input type="text" minlength="3" id="input">Javascript:

let val = document.querySelector("#input");
val.addEventListener('input', () => {
let vaLength = document.querySelector("#input").value
if(vaLength.length >= 5){
console.log("the input has more than 4 character...")
}
})

相关内容

  • 没有找到相关文章