0

As the title says. I'm building my first web application and I wanted to do basic form validation. It works ok, but I have some problems in a method which sends a post request to the server. It sends a request to the server even though I didn't fill all the form's fields and some of the model's properties are empty.

I tried to check every property one by one but there are endless 'if' conditions and I don't believe it's the only solution I have.

Is there any available method which checks if ANY of the given model properties are null?

ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
Aneta
  • 35
  • 1
  • 6
  • 1
    Can you share your validation code, it would be much easier to help – jank Jul 10 '19 at 06:33
  • don't allow form submission if its invalid. also please share some code to help others pinpoint where the problem lies. – kcsujeet Jul 10 '19 at 06:34
  • Give a good read to form validation section of angular documentation [here](https://angular.io/guide/form-validation). Or find a good tutorial on the topic **Angular Form Validation**. There are ways to stop form submission unless all the fields have valid entries. – Johna Jul 10 '19 at 06:36
  • If you don't want an empty value set Validators.required to every form item. This makes the form invalid when not every field is filled in. Then you can simply check the form.valid property before submit. – MoxxiManagarm Jul 10 '19 at 06:41
  • all fields are required? – Pavan Nagadiya Jul 10 '19 at 06:46

2 Answers2

0

Approach 1: Form Validation

Component.html

<form #testForm (ngSubmit)="save()">
 <input  required  [(ngModel)]="model.value1">
 <input  required  [(ngModel)]="model.value2">
 <input type="submit" type="button">
</form>

Component.Ts

 @ViewChild("testForm ") testForm : NgForm | undefined;
 model:any={value1:"",value2:""};

 save()
{
  if( testForm.valid)
   {
      //save  to data base or play
   }    
}

-------------------Approach 2 : Without form-----------------------

Component.ts
//suppose you have model object like below
model:any={value1:"",value2:""};
save()
{
  let valid:boolean=true;
  for(let key of Object.keys(model)
   {
     if(!model[key])
      {
          valid=false;
      }
   }
 if(Valid)
  {
   // save to database or play
  }
}
0

Try using reactive forms. Group your controllers in a form group and add validators to each controller so user cannot process form's data without all required fields completed. Then you can check in OnSubmit function if the form data is invalid (or not) and stop the processing of the data.

Take a look at the following links:

Reactive Forms Angular

Form Validation Angular

You can see my example below:

export class AppComponent implements OnInit {

    registerForm: FormGroup;
    submitted = false;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.registerForm = this.formBuilder.group({
            firstName: ['', Validators.required],
            lastName: ['', Validators.required],
        });
    }

    onSubmit() {
        this.submitted = true;
        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }

        //process data HERE after checking if the form is invalid
    }

}

HTML CODE

<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <label>First Name</label>
        <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
        <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
            <div *ngIf="f.firstName.errors.required">First Name is required</div>
             </div>
        </div>
        <div class="form-group">
            <label>Last Name</label>
            <input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }" />
            <div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
                <div *ngIf="f.lastName.errors.required">Last Name is required</div>
                </div>
            </div>
    </div>
</form>
Paraskevas Louka
  • 223
  • 1
  • 3
  • 10