Home > other >  My required field in my form HTML doesn´t work
My required field in my form HTML doesn´t work

Time:05-17

I have created a in HTML with required fields and then a Submit button with a ng-click=add().

The code is the following:

Enter name:
    <div >
      <label >Enter surname:</label>
      <input type="text"  placeholder="Person surname" ng-model= "newPerson.surname" required>
    </div>
    
    <div >
      <label >Enter age:</label>
      <input type="text"  placeholder="Person age" ng-model= "newPerson.age" required>
    </div>

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

When pressing the button, it adds the person and then it tells me that the fields are required but in my list the person is already there will undefined values.

I have declared on top of the document as well.

Thanks

CodePudding user response:

You can as well use a validation method to validate the inputs on submission instead of required. example

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 >
      <label >Enter surname:</label>
      <input type="text"  placeholder="Person surname" ng-model= "newPerson.surname" required>
    </div>
    <span *ngIf="error.surname"> {{error.surname}}</span>
    <div >
      <label >Enter age:</label>
      <input type="text"  placeholder="Person age" ng-model= "newPerson.age" required>
    </div>
    <span *ngIf="error.age"> {{error.age}}</span>
    <div >
      <label >Enter occupation:</label>
      <input type="text"  placeholder="Person occupation" ng-model= "newPerson.occupation" required>
    </div>
    <span *ngIf="error.occupation"> {{error.occupation}}</span>
    <button type="submit"  ng-click="validateForm()">Add</button>
    
</form>

  • Related