Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Form invalid

I'm making a reactive from in anuglar2. When trying to submit my form, the form says its invalid. I know what is causing the issue, but not how to fix it. For one of my form controls I created a custom validator that checks if its a number. So its required and it has to be a number. If I remove my custom validation on the form, it goes back to being valid. How do I fix this so i can keep my custom validation ?

contact.component.ts

import { Component } from '@angular/core'; 
import { FormBuilder, FormGroup,  Validators } from '@angular/forms'
import { ValidationService } from './validation.service'
@Component({
    selector:'contact', 
    providers:[ValidationService],
    templateUrl:'./contact.component.html'
})
export class ContactComponent {
    public TicketForm = null ; 
    projects:Array<string> = ['Project One','Project Two','Project Three']; 
    constructor(public fb: FormBuilder) {
        this.TicketForm  = fb.group({
            name: [null, Validators.required],
            email: [null, Validators.required],
            phone: [null, Validators.required],
            ticketID: [null, Validators.compose([Validators.required, ValidationService.numberValidation])],
        });
    }
    submit(form:any, isValid:boolean) {
        console.log(form, isValid);
    }
}

Validation.service.ts

import { Injectable } from '@angular/core'; 
import { AbstractControl } from "@angular/forms";

interface ValidationResult {
    [key:string]:boolean;
}
@Injectable()
export class ValidationService {
    constructor() {}
    public static numberValidation(control:AbstractControl): ValidationResult {
        return ({'valid':!isNaN(control.value)}); 
    }
}
like image 826
AJ_ Avatar asked Mar 10 '26 15:03

AJ_


1 Answers

Check this link with the Custom Form Validation part. Based my answer on that.

as jonrsharpe mentioned, null, means that form is valid. Therefore we return null if form is valid, otherwise we return { “numberValidation”: true }

excerpt from link I provided, customized to your example:

One weird thing you might notice is that returning null actually means the validation is valid. If we find a letter we return the validation error { “numberValidation”: true }

So change your validation to something like this:

@Injectable()
export class ValidationService {
    constructor() {}
    public static numberValidation(control: AbstractControl): ValidationResult {
        if (isNaN(control.value)) {
            return { "numberValidation": true }
        }
        return null;
    }
}

and it should work! :)

like image 83
AT82 Avatar answered Mar 13 '26 04:03

AT82