Reputation: 5445
I have one text input that should be required and longer than 3 characters. When I click on it, do nothing (type something shorter than 3 characters) and click out, then I add a red border, otherwise the border will be green.
export class RegisterpageComponent implements OnInit {
userForm: any;
constructor(private formBuilder: FormBuilder) {
this.userForm = formBuilder.group({
login: ["", Validators.required, Validators.minLength(3)]
}
)
}
Here I connect above formBuilder with form and validators with input.
<form [ngFormModel]="userForm" (ngSubmit)="...">
<input class="..." type="text" placeholder="..." ngControl="login" #login="ngForm" />
.
.
.
</form>
sass
input.ng-invalid.ng-touched
border-left: 5px solid red
input.ng-valid.ng-touched
border-left: 5px solid green
Problem is here (I guess) login: ["", Validators.required, Validators.minLength(3)]
1*. When I click on input, leave it empty by clicking out, then I have red border - good. The problem is the border is red whatever I do, even when content of input is longer than 3 characters. Why?
2*. With login validator as login: ["", Validators.minLength(3)]
when I click on input, leave it empty by clicking out, then I have green border. Why? Red border is when content of input is longer than 3 characters (here that validator works)
3*. With login validator as ["", Validators.minLength(3)]
and HTML code like <input class="..." type="text" placeholder="..." ngControl="login" #login="ngForm" required />
finally I have what I wanted - when I click on input, leave it empty by clicking out - red border (good), when I type something longer than 3 characters - green border (good). Why 2* doesn't work like that?
Finally - what is the [""
as the first parameter of validators set? Thank you guys!
Upvotes: 1
Views: 597
Reputation: 95
Please create form this way and update your component because you have created your validators of minlength in async validators
this.userForm = formBuilder.group({
login: ["", [Validators.required,Validators.minLength(3)]]
}
<form role="form" [formGroup]="userForm" (ngSubmit)="onSubmit(userForm)">
<div>
<input formControlName="login">
</div>
</form>
Upvotes: 1
Reputation: 1059
Try like this. It works for me.
this.formvalid = new FormGroup({
login: new FormControl('', [Validators.required, Validators.minLength(3)])
});
<div [formGroup]=" formvalid">
<label id="label" >Cheque No</label>
<span *ngIf="formvalid.controls.login.status == 'INVALID' && formvalid.touched" class="required" aria-required="true"> * </span>
<input type="text" formControlName="login" [(ngModel)]="login" class="form-control form-control-sm" placeholder="login">
</div>
In the input field it will allow type less than 3 characters. But if input field is not valid, it will indicate form is invalid by indicating span (*).
Upvotes: 1
Reputation: 449
Try the next:
this.userForm = formBuilder.group({
login: ["", Validators.compose([ Validators.required, Validators.minLength(3) ])
});
Upvotes: 1