1

my code as below:

html

<form [formGroup]="demo2Group">
        <input formControlName="demo2Value">
        <div *ngIf="demo2Value.invalid && (demo2Value.dirty || demo2Value.touched)">
            <div *ngIf="demo2Value.errors.required">
                the value can't be empty
            </div>
            <div *ngIf="demo2Value.errors.minlength">
                the value can't less than 4 length
            </div>
            <div *ngIf="demo2Value.errors.maxLength">
                the value can't more than 6 length
            </div>
        </div>
    </form>

ts

demo2Group;
ngOnInit() {
    this.demo2Group = new FormGroup({
        'demo2Value': new FormControl(null, [
            Validators.required,
            Validators.minLength(4),
            Validators.maxLength(6),
        ])
    });
}
get demo2Value() { return this.demo2Group.get('demo2Value'); }

The required and minlength works,but the maxLength didn't work.If I use template validation.The input element can't input more than 6.

But now,I can input more than 6 and didn't show any error.

1 Answer 1

1

Try something like this:

DEMO

HTML:

maxLength ----> 'maxlength'

<h1>
    Reactive Form Validation</h1>

<form [formGroup]="demo2Group">
    <input formControlName="demo2Value">

    <div *ngIf="demo2Group.get('demo2Value').hasError('required') && demo2Group.get('demo2Value').touched">
        the value can't be empty
    </div>
    <div *ngIf="demo2Group.get('demo2Value').hasError('minlength')">
        the value can't less than 4 length
    </div>
    <div *ngIf="demo2Group.get('demo2Value').hasError('maxlength')">
        the value can't more than 6 length
    </div>

</form>

TS:

demo2Group: FormGroup;

  constructor(private fb: FormBuilder) {

  }

  ngOnInit() {
    this.demo2Group = this.fb.group({
      demo2Value: [null, [Validators.required, Validators.minLength(4),
      Validators.maxLength(6),
      ]]
    });

  }
Sign up to request clarification or add additional context in comments.

5 Comments

Thx,it works.Can you tell me why my code's error?If all the validators do not work,I can understand.But only maxLength didn't work.I am confused.
you should not put all validation together put them separate.or you can create common component for that.
Do not put all validation together? why not?
and you are using 'maxLength'' update it with 'maxlength'. hope you understood??
OMG! That's true! I thought two words are same.I understand it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.