我的表单 HTML 中的必填字段不起作用

My required field in my form HTML doesn´t work

我在 HTML 中创建了一个包含必填字段的按钮,然后是一个带有 ng-click=add() 的提交按钮。

代码如下:

输入名字:
    <div class="mb-3">
      <label class="form-label">Enter surname:</label>
      <input type="text" class="form-control" placeholder="Person surname" ng-model= "newPerson.surname" required>
    </div>
    
    <div class="mb-3">
      <label class="form-label">Enter age:</label>
      <input type="text" class="form-control" placeholder="Person age" ng-model= "newPerson.age" required>
    </div>

    <div class="mb-3">
      <label class="form-label">Enter occupation:</label>
      <input type="text" class="form-control" placeholder="Person occupation" ng-model= "newPerson.occupation" required>
    </div>
    
    <button type="submit" class="btn btn-primary" ng-click="add()">Add</button>
    
</form>

当按下按钮时,它添加了这个人,然后它告诉我这些字段是必填的,但在我的列表中这个人已经存在,将是未定义的值。

我也在文件上面声明了。

谢谢

您也可以使用验证方法来验证提交时的输入,而不是必需的。 例子

public validateForm() {
  if(newPerson.surname === null || 
  newPerson.surname === undefined || newPerson.surname === " ")
  {
    error.surname = "Surname is required";
  }
  if(newPerson.age === null || 
  newPerson.age === undefined || newPerson.age === " ")
  {
    error.age = "Age is required";
  }
  if(newPerson.occupation === null || 
  newPerson.occupation === undefined || newPerson.occupation === " ")
  {
    error.occupation = "Occupation is required";
  }
  
  if(newPerson.surname !== null || 
  newPerson.surname !== undefined || newPerson.surname !== " " ||
  newPerson.age !== null || 
  newPerson.age !== undefined || newPerson.age !== " " ||
  newPerson.occupation !== null || 
  newPerson.occupation !== undefined || newPerson.occupation !== "
  )
  {
    this.add();
  }

}
  <div class="mb-3">
      <label class="form-label">Enter surname:</label>
      <input type="text" class="form-control" placeholder="Person surname" ng-model= "newPerson.surname" required>
    </div>
    <span *ngIf="error.surname"> {{error.surname}}</span>
    <div class="mb-3">
      <label class="form-label">Enter age:</label>
      <input type="text" class="form-control" placeholder="Person age" ng-model= "newPerson.age" required>
    </div>
    <span *ngIf="error.age"> {{error.age}}</span>
    <div class="mb-3">
      <label class="form-label">Enter occupation:</label>
      <input type="text" class="form-control" placeholder="Person occupation" ng-model= "newPerson.occupation" required>
    </div>
    <span *ngIf="error.occupation"> {{error.occupation}}</span>
    <button type="submit" class="btn btn-primary" ng-click="validateForm()">Add</button>
    
</form>