使用 javascript 设置文本输入字段所需的最小长度?

我希望能够根据用户输入的字符数来执行验证 - 我希望至少有 7 个字符。(最大值是使用 HTML 属性设置的) - 我尝试了以下方法:


v3 = document.getElementById("npo-registration-number");

flag3 = true;


if (val >= 3 || val == 0) {

        if (v3.value == "") {

            v3.style.borderColor = "red";

            flag3 = false;

        }

        else if (v3.value.length === 7){

            v3.style.borderColor = "green";

            flag3 = true;

        }

   }

上述方法在一定程度上有效。仅当输入 7 个字符时,输入字段边框颜色才会显示绿色。但是,如果我从该点开始删除字符,边框将保持绿色。任何有关此事的帮助都将受到赞赏。


守候你守候我
浏览 156回答 5
5回答

一只萌萌小番薯

我不完全确定你想要什么;这接近您要寻找的吗?您可能执行了此操作,但没有将其包含在您的代码片段中,但我们需要在每次编辑表单时运行它。我们向输入添加一个事件侦听器。const input = document.getElementById('npo-registration-number');input.addEventListener('input', () => {&nbsp; &nbsp; // set the border to red if the value is < 7 characters&nbsp; &nbsp; if (input.value.length < 7) {&nbsp; &nbsp; &nbsp; &nbsp; input.style.borderColor = 'red';&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; // otherwise, set it to green&nbsp; &nbsp; input.style.borderColor = 'green';});这解决了一个问题:除非表单的值是空字符串,否则不要将边框的颜色设置为红色。相反,当输入长度低于 7 时,我们希望边框为红色。

弑天下

您需要捕获input事件,以便 js 可以评估和更新。     const ev3 = document.getElementById("npo-registration-number");     let flag3 = true;     ev3.addEventListener('input', (e) => {       const val = e.target.value;       if (val.length === 7){                ev3.style.borderColor = "green";                flag3 = true;                  }        else {           ev3.style.borderColor = "red";           flag3 = true;           }     });input {  outline: 0;  border: 1px solid;}<input id="npo-registration-number" type='text'>

波斯汪

您可以只使用为其运行此功能的按钮,例如send或post按钮(许多网站使用此方法)。function click(){&nbsp; v3 = document.getElementById("npo-registration-number");&nbsp; flag3 = true;&nbsp; if (val >= 3 || val == 0) {&nbsp; &nbsp; &nbsp; &nbsp; if (v3.value == "") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v3.style.borderColor = "red";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flag3 = false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else if (v3.value.length === 7){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v3.style.borderColor = "green";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flag3 = true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}

呼唤远方

是因为你的条件if (v3.value == "") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v3.style.borderColor = "red";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flag3 = false;&nbsp; &nbsp; &nbsp; &nbsp; }当您开始删除输入中的字符时,您的输入不会再次变为红色,因为仅当没有字符时它才是红色,并且输入 7 个字符后它会变为绿色。

白衣染霜花

请尝试这个v3 = document.getElementById("npo-registration-number");flag3 = true;if (v3.value == "") {&nbsp; &nbsp;v3.style.borderColor = "red";&nbsp; &nbsp;flag3 = false;&nbsp;} else {&nbsp;if (v3.value.length < 7){&nbsp; &nbsp; v3.style.borderColor = "red";&nbsp; &nbsp; flag3 = false;&nbsp; &nbsp; }&nbsp;else {&nbsp; &nbsp; v3.style.borderColor = "green";&nbsp; &nbsp; flag3 = true;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript