How can I solve the same issue in Angular, that ng-messages solved in AngularJS?

前端 未结 3 1518
盖世英雄少女心
盖世英雄少女心 2021-02-12 13:44

In AngularJS there was a form directive named ng-messages which helped us to make it so that not all form errors showed at the same time. So that for example if an input has 3 e

3条回答
  •  余生分开走
    2021-02-12 14:13

    Next to my other answer, you could also use a library I've created called angular-reactive-validation which can be found here.

    You indicate that showing at most one validation message per control at any given time is important to you. This library supports that behaviour. It also reduces the amount of HTML you need to write to show validation messages, because the declaration of validation messages is moved to the Component where you declare your FormControls. Another handy feature is having dynamic validation values by passing a function to the Validator.

    Below I've provided an example form and the model behind it to give you an idea of the basic usage.



    import { Validators } from 'angular-reactive-validation';
    ...
    
    form = this.fb.group({
      name: this.fb.group({
        firstName: ['', [Validators.required('A first name is required'),
          Validators.minLength(1, minLength => `The minimum length is ${minLength}`),
          Validators.maxLength(50, maxLength => `Maximum length is ${maxLength}`)]],
        middleName: ['', [Validators.maxLength(50, maxLength => `Maximum length is ${maxLength}`)]],
        lastName: ['', [Validators.required('A last name is required'),
          Validators.maxLength(50, maxLength => `Maximum length is ${maxLength}`)]]
      }),
      age: [null, [
        Validators.required('An age is required'),
        Validators.min(0, 'You can\'t be less than zero years old.'),
        Validators.max(150, max => `Can't be more than ${max}`)
      ]]
    });
    

提交回复
热议问题