I'm trying to set a pattern validator in my angular form. No matter how I put it in, it doesn't validate the pattern. I created a simple reproducible example. the [(ngModel)]="".. has to remain. I thaught if I used simple html this would work, but it doesn't. In this example I followed the below link and inserted in my exisiting angular code. It states clearly that 'pattern' gets validated on form submission.
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern
The problem with using thing like formbuilder, which I can find online tutorials regarding validating in Angular, is that it witholds me from using the [(ngModel)]. In need to be able to implement it in my exisiting form.
app.component.html
<h1>form</h1>
<form role="form" (submit)="testpattern()" #testForm="ngForm">
<input required type="text" name="riziv" [pattern]="[0-9]" [(ngModel)]="inputform.riziv">
<button type="submit" (onclick)="testpattern()">test pattern</button>
</form>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'testout';
inputform={riziv:''};
constructor(
) { }
testpattern(): void {
console.log(this.inputform.riziv);
}
}
No matter what I put in, nothing gets validated by the pattern. The console just logs whatever I put in. How do I make this validate when using [(ngModel)]?
CodePudding user response:
The pattern works just fine. It is the submit button that is configured wrong. When I added
[disabled]="adduserForm.form.invalid"
the button only gets abled when the pattern is formed correctly.