【问题标题】:Cannot verify if password is empty无法验证密码是否为空
【发布时间】:2019-10-20 22:30:22
【问题描述】:

我正在验证一个表单,我想在密码无效时显示一条消息,使用 RegExp 进行验证,但前提是它不为空,但我无法验证密码是否为空。 这是我指的那段代码。

const regexPasswd: RegExp = /((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,64})/;
    const inputPasswd = $(form).find("[name='passwd']");
    const passwd;
    let allOK = true;
    if (inputPasswd.val() !== undefined || inputPasswd.val() !== "" || inputPasswd.val() !== null) {
          if (this.regexPasswd.test(<string>inputPasswd.val())) passwd = inputPasswd.val();
          else {
            message += "Invalid Password<br>";
            allOK = false;
          }
        }

我已经尝试了所有三种我知道的方法来验证空输入,但仍然不起作用。 提前感谢您的帮助。

【问题讨论】:

  • 在您的情况下应该是 &amp;&amp; 运算符而不是 ||
  • var pwd = $(form).find("[name=passwd]").val() || "" 然后检查if (pwd === "")
  • 这是什么构造? this.regexPasswd.test(&lt;string&gt;inputPasswd.val()))

标签: javascript jquery html regex ecmascript-6


【解决方案1】:

在条件中使用&amp;&amp;(逻辑与)而不是||(逻辑或)并缓存值:

let val = $.trim(inputPasswd.val()); 
if (val !== undefined && val !== "" && val !== null) {...}

【讨论】:

  • 没问题@zarzanduil,总是乐于提供帮助。
【解决方案2】:

有人指出你关于 || 的错误和&&

但我想指出 HTML 提供了一种更简单的解决方案!

首先,您可以添加一个Required 属性。如果该字段中没有任何内容,则无法提交表单。

其次,您可以使用 minlength 设置所需的最小长度。但是对于 1 这有点多余,因为您需要这样做

希望这会有所帮助!

<label for="name">Name (4 to 8 characters):</label>

<form>
<input type="text" id="name" name="name" required
       minlength="1" maxlength="12" size="12">
       
<input type="submit" value="test">

【讨论】:

  • 对不起朋友,我没有解释清楚。我想要的不是在密码为空时显示消息,而是在检查其格式时仅在密码不为空时显示。我现在已经编辑了这个问题。不过谢谢你的帮助!
  • 没问题!感谢您不投反对票,因为这不是您想要的!
【解决方案3】:

简单写

const regexPasswd: RegExp = /((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,64})/;
    const inputPasswd = $(form).find("[name='passwd']");
    const passwd;
    let allOK = true;
    if (!inputPasswd.val().length == 0 || inputPasswd.val() )  
    {
     // if value length is non-zero or non-undefined or non-null 

          if (this.regexPasswd.test(<string>inputPasswd.val())) passwd = inputPasswd.val();
          else {
            message += "Invalid Password<br>";
            allOK = false;
          }
        }

【讨论】:

  • if ($.trim(inputPasswd.val()).length &gt; 0) 更有意义
  • 不应该是:if (inputPasswd.val() &amp;&amp; inputPasswd.val().length !== 0) 吗? - 为清晰起见移动了!,但应在调用.length 之前检查.va() 是否不为空,否则会出现错误
  • 长度属性没问题,但我在 Type Script 文件中写了这个
  • @freedomn-m 仅供参考!如果你在 if 语句中写 null 你会得到 false 并且 if (inputPasswd.val() && inputPasswd.val().length !== 0) 和 (!inputPasswd.val().length == 0 || inputPasswd .val() ) 是一回事
  • @DanialShabbir 让我们测试一下:var x = null; if (x.length == 1 || x == null) console.log("it works") - 哦,看 - 那是 false 吗?不,是Uncaught TypeError。在 javascript 中,使用 || 它首先运行左侧测试,在这种情况下会给出错误,而不是 null - 为了完整性,如果 || 的左侧是true 然后它停止并且不再运行(与使用函数时相关)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2011-04-25
  • 2011-11-27
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多