According to thoughtgram.io, the currently supported validators are:
- required
- minlength
- maxlength
- pattern
So, considering the following code (plunkr here):
@Component({
selector: 'my-app',
template: `
<form #formRef="ngForm">
<input type="number" [(ngModel)]="firstValue" name="firstValue" min="0" required/>
<input type="text" [(ngModel)]="secondValue" maxlength="5" name="secondValue" required/>
<button type="submit"> Submit </button>
</form>
FORM: {{formRef.form | json }}
`
})
export class AppComponent {
firstValue = -22;
secondValue = "eyy macarena!";
}
While minlength
is supported, min="0"
is ignored by angular validation:
So, to make the form result in an error when firstValue ngModel < 0, do I need to build a custom validator?
In your code you are using
min
and notminlength
. Please also notice that this will not validate if a number is > 0 but its length.I found a library implementing a lot of custom validators - ng2-validation - that can be used with template-driven forms (attribute directives). Example:
Create a service NumberValidatorsService and add validator functions:
Import service into module.
Add includes statement in component where it is to be used:
Add validators to form builder:
In the template, you can display the errors as follows:
As far as I know, is it implemented now, check https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts
This is the part that implements what you are looking for:
I've found this as a solution. Create a custom validator as follow
and under constructor include the below code
where customForm is a FormGroup and _builder is a FormBuilder.
Apparently, Angular had the max/min directives for template driven forms at some point but had to remove them in v4.2.0. You can read about the regression that caused the removal here: https://github.com/angular/angular/issues/17491
For now the only working solution that I know of is to use custom directive as @amd suggested. Here's how to use it with Bootstrap 4.
min-validator.directive.ts
And in your template:
Hope this helps!