ts file:
myForm: FormGroup = new FormGroup({
Id: new FormControl("",[Validators.pattern('^.{1,50}$')])
});
addEntry(){
this.finalmsg =[];
let class = '';
let msg = '';
let snackbar = new SnackbarComponent(this.snackbar);
if(this.myForm.controls['Id'].invalid){
msg = 'Enter between 1 to 50';
class = 'redsnackbar';
this.finalmsg.push(msg);
snackbar.openSnackBar(this.finalmsg, "Close", class);
}
this.dialogRef.close("OK")
}
This is the code I am using to validate the input field. It works opposite of how it should If I change from invalid to valid then the snackbar is displayed. And when its invalid, then it does not go in the loop the dialog is closed. What can be the issue?
CodePudding user response:
The Expression you used is what causes the problem , replace the Regex to the following :
myForm: FormGroup = new FormGroup({
//YOU SHOULD TELL THE `Validators` TO only allow digit from 0 to 50 and no
//other character should be allowed
Id: new FormControl("",[Validators.pattern('^[1-9]$|^[1-9][0-9]$|^(50)$')])
});
addEntry(){
this.finalmsg =[];
let class = '';
let msg = '';
let snackbar = new SnackbarComponent(this.snackbar);
if(this.myForm.controls['Id'].invalid){
msg = 'Enter between 1 to 50';
class = 'redsnackbar';
this.finalmsg.push(msg);
snackbar.openSnackBar(this.finalmsg, "Close", class);
}
this.dialogRef.close("OK")
}
Enjoy
CodePudding user response:
The Regex patterns (in general, not just in Angular) are used to examine the structure of a string, and not to understand its potential meaning or value (such as eg.a number). The pattern you used in your question tells the validator that it expects a string that is from 1 to 50 characters in length, inclusively. Whereas, telling by the error message you show, you are after a value which, as a number, falls into a range 1 to 50.
Change this line:
Id: new FormControl("",[Validators.pattern('^[1-9]$|^[1-9][0-9]$|^(50)$')])
to this:
Id: ['', Validators.compose([ Validators.required, Validators.min(1), Validators.max(50) ])]
(of course adjust the boundaries depending on inclusive/exclusive variant)
or, if you are after the string length, use Validators.minLength(...)
and Validators.maxLength(...)
accordingly