javascript - 必填字段的验证函数较短

标签 javascript html validation typescript

在带有 typescript 的 HTML 应用程序中,我有一个 HTML 表单。该表格有一些必填字段。在我的 typescript 文件中,我正在构建如下错误消息:

hasErrors() {
    let errorCount = 0;

    if (!item.Field1()) {
        this.ErrorText('"Field1"');
        errorCount++;
    }
    if (!item.Field2()) {
        if (errorCount > 0)
            this.ErrorText(this.ErrorText() + ', "Field2"');
        else
            this.ErrorText('"Field2"');
        errorCount++;
    }
    if (!item.Field3()) {
        if (errorCount > 0)
            this.ErrorText(this.ErrorText() + ', "Field3"');
        else
            this.ErrorText('"Field3"');
        errorCount++;
    }

    // ...

    if (errorCount > 1)
        this.ErrorText("The fields " + this.ErrorText() + " are required.";
    else if (errorCount == 1)
        this.ErrorText("The field " + this.ErrorText() + " is required.";
    else
        return false;
    return true;
}

如您所见,如果需要很多字段,则该函数会变得很长。有没有更好/更短的方法来获得相同的结果?

最佳答案

这将显示默认需要消息

  <form action="includes/loginprocess.php" method="POST">
    <input type="text" name="user" placeholder="Username" required>
    <input type="password"name="pass" placeholder="Password" required>
    <input type="submit" value="Login">
  </form>

关于javascript - 必填字段的验证函数较短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405222/

相关文章:

验证期间发现的 iOS 问题 - 无效字符

javascript - SharePoint 2013 View 中所有浏览器中的 .js MIME 类型错误

javascript - 当新的 props 被传递时,React 子组件状态不会更新

javascript - 将 FullCalendar 事件填充为数组 - 从另一个数组填充

html - 如何停止在浏览器中显示加载图标

asp.net - 链接到页面上的不同区域

html - 对齐 Span 的内容

javascript - 好的编程,我应该重用值吗?

php - 如何开始使用PHP创建自定义支付系统?

javascript - 使用嵌套对象的 Hapi/Joi 验证