Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  177] [ 4]  / answers: 1 / hits: 38548  / 8 Years ago, fri, november 18, 2016, 12:00:00

I have a form with input boxes. The input boxes are in both type text and numbers. And I have to validate them and I followed this tutorial and tried to validate them.


According to that if I have to validate a string then I can use the control group as follows.


constructor(fb: FormBuilder){
this.complexForm = fb.group({
'firstName' : [null, Validators.required],
'lastName': [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]
})

And the HTML code for this as follows...


<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
<div class="form-group">
<label>First Name:</label>
<input class="form-control" type="text" placeholder="John" [formControl]="complexForm.controls['firstName']">
</div>
<div class="form-group">
<label>Last Name</label>
<input class="form-control" type="text" placeholder="Doe" [formControl]="complexForm.controls['lastName']">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>

But I have to validate a number type input box also as the following example.


<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
<div class="form-group">
<label>Age:</label>
<input class="form-control" type="number" [formControl]="complexForm.controls['age']">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>

But Problem is there is no option for Validators to select what is minimum value and maximum value for the input.


are there someone has a solution for this issue?


Thanks.


More From » forms

 Answers
20

There's no built-in Validator for min/max currently you can checkout the source for Validator to see whats available.



What you can do is create a custom validator function following the tutorials in the official docs



Example:



export function maxValue(max: Number): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const input = control.value,
isValid = input > max;
if(isValid)
return { 'maxValue': {max} }
else
return null;
};
}


With this you can update your code to



constructor(fb: FormBuilder){
this.complexForm = fb.group({
'firstName' : [null, Validators.required],
'lastName': [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])],
'age': [null, maxValue(60)]
})

[#60017] Wednesday, November 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;