Home > other >  validation for string input field in reactive forms
validation for string input field in reactive forms

Time:12-23

This is my form and this shows errors only while clicking on submit button

I want this error to be shown while typing in the input field.

validation for string input field in reactive forms, when numbers are typed errors should be shown immediately like (enter only numbers), and when the numbers are removed the error should not be shown. pls, any ideas?

CodePudding user response:

Depending on the number format you could use an input of type="number".

As for validation, use the updateOn: 'change' option in your required every FormControl that needs to validate on change, like this:

mobile: [
    null, {
        validators: [
            // your validators here
        ],
        asyncValidators: [
            // your async validators here
        ],
        updateOn: 'change'
    }
]

This way the validators will be called everytime the value of the control changes, i.e. with every keypress.

CodePudding user response:

Next time you can add your code. You have to create an text to show when they are a error in a field, or add something like red border on input

<div [formGroup]="form">
  <label for="title" >Title</label>
  <span
    
    *ngIf="form.get('title').errors &&
        form.get('title').hasError('required')">min 2 length</span>
  <input id="title" type="text" placeholder="" formControlName="title">
</div>

on typescript ( don't forget to import formGroup and formBuilder)

form: FormGroup = new FormGroup({});

constructor(private fb: FormBuilder) {
  this.form = this.fb.group({
  title: ['', [Validators.required, Validators.minLength(2)]]
  });
}

on css

.text-danger{
   color: red
 }

you can also directly add on input this code ( and create in css class valid and invalid)

[class.valid]="formGroup.get('title').valid && 
    (formGroup.get('title').dirty || formGroup.get('title').touched)"
[class.invalid]="formGroup.get('title').invalid && 
    (formGroup.get('title').dirty || formGroup.get('title').touched)"

CodePudding user response:

Try this amazing library called React-hook-form

In this library, There are 4 stages of getting data from the form inputs.

Recently, I've used it and it's very amazing and straight forward to use... Please visit the official website and watch those 2 videos.

  • Related