Reputation: 38
I'm trying to create some simple reactive validation for at project, but it keeps returning it as "Valid" even though it shouldn't be. I'm trying to validate the length of a number, which must be between 7-16 digits.
card-add-c.component.html
<h1>Add credit card</h1>
<form [formGroup]="addCardForm"> <!-- (ngSubmit)="onSubmit()">-->
<div class="cross-validation" [class.cross-validation-error]="addCardForm.errors?.identityRevealed && addCardForm.touched">
<label for="card_number">Card number</label>
<input type="number" id="card_number" class="form-control" formControlName="card_number" required>
<label *ngIf="card_number.invalid && card_number.touched" class="alert alert-danger">
<div *ngIf="card_number.errors?.minLength">
Name must be at least 7 characters long.
</div>
<div *ngIf="card_number.errors?.maxlength">
Name must be 16 or less characters long.
</div>
</label>
</div>
<button class="button" type="submit" [disabled]="!addCardForm.valid">Add card</button>
<p>Form Status: {{ addCardForm.status }}</p>
</form>
card-add-c.component.ts
import { Component, OnInit } from '@angular/core';
import { cardService } from '../credit-card.service';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Validators } from '@angular/forms';
@Component({
selector: 'app-card-add-c',
templateUrl: './card-add-c.component.html',
styleUrls: ['./card-add-c.component.css']
})
export class CardAddCComponent implements OnInit {
ngOnInit(): void {
}
addCardForm = this.formBuilder.group({
card_number: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(16)]),
// more here, but currently commented out, as I'm working on only card_number
})
constructor(
private cardService: cardService,
private formBuilder: FormBuilder,
) { }
card = this.cardService.addCard(this.addCardForm.value);
onSubmit():void{
this.cardService.addCard(this.addCardForm.value).subscribe(res =>{
console.log("Card " + this.addCardForm.value + " added!");
})
console.log("Card added");
}
get card_number() {
return this.addCardForm.get('card_number')!;
}
}
I've looked at a lot of documentation, and is should work, but it doesn't. The requried statement works, but not the lengths. Any idea on what I'm doing wrong?
Outputs:
Startup:
Too few
Too many
Upvotes: 0
Views: 1183
Reputation: 4464
minLength
and maxLength
are for strings, but your input type is a number
.
Given a credit card can start with 0
, you might want to change the input wit text
and maybe check only numbers are there.
Upvotes: 1