2016-04-04 29 views
2

在使用打字稿的HTML应用程序中,我有一个HTML表单。该表格有一些必填字段。在我的打字稿文件我建立一个错误信息是这样的:所需字段的较短验证功能

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; 
} 

正如你可以看到,这个功能会非常长,如果有需要,许多领域。有没有更好/更短的方式来获得相同的结果?

回答

1
function catErrors(field){ 
    if (!item.field) { 
     if (this.errorCount > 0) 
      this.ErrorText(this.ErrorText() + ', "' + field + '"'); 
     else 
      this.ErrorText('"' + field + '"'); 
     this.errorCount++; 
    } 
} 

你可能创建一个函数来寻找错误吗? 你可以这样调用函数:catErrors(Field1)
这将有助于缩短您的代码。您只需手动添加第一个字段即可开始,随后的所有内容都将使用功能catErrors()。希望这可以帮助!

+0

谢谢,这就是我一直在寻找的。 –

3

这会显示默认需要味精

<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> 
0

来想一想,你是想告诉用户哪些空白它们丢失。它真的很需要吗?如何检测缺失的空白并返回“字段xxx缺失”消息?例如,你有两个空格,用户名和密码,如果用户没有填写他们,你可以指出“用户名是必需的”。