angularangular-custom-validators

Validators angular


I am trying to force Validators.required for the password field in the same modal. If it is an update, it will not catch Validators.required otherwise it will get an error. Help me! Thanks you!

userForm() {
  const special = /^[A-Za-z0-9]+[A-Za-z0-9\-\_]*$/;
  this.UserForm = this.formBuilder.group({
    username: ['', [Validators.required, Validators.pattern(special)]],
    birthDate: ['', [Validators.required]],
    gender: [0, [Validators.required]],
    password: ['', [this.ifEditUser ? Validators.required : '', Validators.maxLength(64)]],
    fullName: ['', [Validators.required, Validators.maxLength(255)]],
    passwordRe: ['']
  },
  {
    validator: MustMatch('password', 'passwordRe')
  });

}


Solution

  • You need to remove single inverted comma after Validators.required like as following

    userForm() {
      this.UserForm = this.formBuilder.group({
        password: ['', [this.ifEditUser ? Validators.required : Validators.maxLength(64)]]
      });
    }
    

    For showing error use this below code

    <small class="form-text text-danger" *ngIf="UserForm.controls.password.errors && !ifEditUser">
      Maximum 64 characters are allowed.
    </small>
    

    and also add this following line with submit button. Submit button will automatically disable when your form is not valid.

    <input [disabled]="!UserForm.valid" type="submit">
    

    I hope it is helpful for you. :)