Angular: Custom validation with parameter












0















I am trying to implement a verify password validation with Angular 6 using Reactive Form but I can't get the best way to do it, below an example that works with "1234" but I would like to pass the value of the password control instead.
I tried with ValidatePWD(this) but doesn't work either.



 //component.ts
import { ValidatePWD } from './compare.validator';

this.form = this._fb.group({
'user': ['', Validators.compose([Validators.required])],
'password': ['', Validators.compose([Validators.required])],
'verifypassword': ['', [Validators.required, ValidatePWD]],

});


//compare.validator.ts
import { AbstractControl, FormGroup } from '@angular/forms';
export function ValidatePWD(control: AbstractControl ) {
if (control.value != "1234") {
return { validPWD: true };
}
return null;
}


<div class="form-group">
<label>Password: {{model.password}}</label>
<input [(ngModel)]="model.password" [formControl]="password" class="form-control" type="password">
</div>

<div class="form-group">
<label >Verify Password</label>
<input[(ngModel)]="model.verifypassword" [formControl]="verifypassword" class="form-control" type="password">
</div>


enter image description here
Thanks
Andrea










share|improve this question





























    0















    I am trying to implement a verify password validation with Angular 6 using Reactive Form but I can't get the best way to do it, below an example that works with "1234" but I would like to pass the value of the password control instead.
    I tried with ValidatePWD(this) but doesn't work either.



     //component.ts
    import { ValidatePWD } from './compare.validator';

    this.form = this._fb.group({
    'user': ['', Validators.compose([Validators.required])],
    'password': ['', Validators.compose([Validators.required])],
    'verifypassword': ['', [Validators.required, ValidatePWD]],

    });


    //compare.validator.ts
    import { AbstractControl, FormGroup } from '@angular/forms';
    export function ValidatePWD(control: AbstractControl ) {
    if (control.value != "1234") {
    return { validPWD: true };
    }
    return null;
    }


    <div class="form-group">
    <label>Password: {{model.password}}</label>
    <input [(ngModel)]="model.password" [formControl]="password" class="form-control" type="password">
    </div>

    <div class="form-group">
    <label >Verify Password</label>
    <input[(ngModel)]="model.verifypassword" [formControl]="verifypassword" class="form-control" type="password">
    </div>


    enter image description here
    Thanks
    Andrea










    share|improve this question



























      0












      0








      0








      I am trying to implement a verify password validation with Angular 6 using Reactive Form but I can't get the best way to do it, below an example that works with "1234" but I would like to pass the value of the password control instead.
      I tried with ValidatePWD(this) but doesn't work either.



       //component.ts
      import { ValidatePWD } from './compare.validator';

      this.form = this._fb.group({
      'user': ['', Validators.compose([Validators.required])],
      'password': ['', Validators.compose([Validators.required])],
      'verifypassword': ['', [Validators.required, ValidatePWD]],

      });


      //compare.validator.ts
      import { AbstractControl, FormGroup } from '@angular/forms';
      export function ValidatePWD(control: AbstractControl ) {
      if (control.value != "1234") {
      return { validPWD: true };
      }
      return null;
      }


      <div class="form-group">
      <label>Password: {{model.password}}</label>
      <input [(ngModel)]="model.password" [formControl]="password" class="form-control" type="password">
      </div>

      <div class="form-group">
      <label >Verify Password</label>
      <input[(ngModel)]="model.verifypassword" [formControl]="verifypassword" class="form-control" type="password">
      </div>


      enter image description here
      Thanks
      Andrea










      share|improve this question
















      I am trying to implement a verify password validation with Angular 6 using Reactive Form but I can't get the best way to do it, below an example that works with "1234" but I would like to pass the value of the password control instead.
      I tried with ValidatePWD(this) but doesn't work either.



       //component.ts
      import { ValidatePWD } from './compare.validator';

      this.form = this._fb.group({
      'user': ['', Validators.compose([Validators.required])],
      'password': ['', Validators.compose([Validators.required])],
      'verifypassword': ['', [Validators.required, ValidatePWD]],

      });


      //compare.validator.ts
      import { AbstractControl, FormGroup } from '@angular/forms';
      export function ValidatePWD(control: AbstractControl ) {
      if (control.value != "1234") {
      return { validPWD: true };
      }
      return null;
      }


      <div class="form-group">
      <label>Password: {{model.password}}</label>
      <input [(ngModel)]="model.password" [formControl]="password" class="form-control" type="password">
      </div>

      <div class="form-group">
      <label >Verify Password</label>
      <input[(ngModel)]="model.verifypassword" [formControl]="verifypassword" class="form-control" type="password">
      </div>


      enter image description here
      Thanks
      Andrea







      angular typescript angular-reactive-forms






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 13:32







      Gelso77

















      asked Nov 13 '18 at 11:13









      Gelso77Gelso77

      303114




      303114
























          1 Answer
          1






          active

          oldest

          votes


















          0















          Option 1 - Validate the password and verifyPassword through FormGroup,




          Here is simple sample code for confirm password validation where you need to pass the validator to FormGroup which contains both the contols password and confirmPassword.



            this.form = this._fb.group({
          'user': ['', Validators.compose([Validators.required])],
          'password': ['', Validators.compose([Validators.required])],
          'verifypassword': ['', [Validators.required]],

          }, { validator: this.passwordMatchValidator });

          passwordMatchValidator(g: FormGroup) {
          return g.get('password').value === g.get('verifypassword').value
          ? null : {'mismatch': true};
          }


          html



          <div *ngIf="form.invalid && form.errors['mismatch']">Password did not match</div>


          Sample example is here -https://stackblitz.com/edit/confirm-password-q3ngps




          Option 2 - Use a function to match the password.




          password-validator.ts



          export class PasswordValidation {

          static MatchPassword(AC: AbstractControl) {
          let password = AC.get('password').value;
          if(AC.get('confirmPassword').touched || AC.get('confirmPassword').dirty) {
          let verifyPassword = AC.get('confirmPassword').value;

          if(password != verifyPassword) {
          AC.get('confirmPassword').setErrors( {MatchPassword: true} )
          } else {
          return null
          }
          }
          }
          }


          Component ts



          this.form = this._fb.group({
          password: ['', Validators.required],
          confirmPassword: ['', Validators.required]
          }, {
          validator: PasswordValidation.MatchPassword
          });


          Working copy is here - https://stackblitz.com/edit/material-password-confirm-pnnd4t






          share|improve this answer


























          • it works but only when i press the submit button, i wuold like to check the validation as soon as the user touch the verifypassword field

            – Gelso77
            Nov 13 '18 at 11:35











          • I think you had put the condition in html when to show the error. Share your html.

            – Sunil Singh
            Nov 13 '18 at 11:38











          • updated,many thank Sunil!

            – Gelso77
            Nov 13 '18 at 11:52











          • I don't see the error message in your given html.

            – Sunil Singh
            Nov 13 '18 at 11:55











          • just because i am using the css ng-valid, ng-invalid, you know the validation password if is differents must be invalid ...after that if is invalid i can add a message

            – Gelso77
            Nov 13 '18 at 12:10













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53279777%2fangular-custom-validation-with-parameter%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0















          Option 1 - Validate the password and verifyPassword through FormGroup,




          Here is simple sample code for confirm password validation where you need to pass the validator to FormGroup which contains both the contols password and confirmPassword.



            this.form = this._fb.group({
          'user': ['', Validators.compose([Validators.required])],
          'password': ['', Validators.compose([Validators.required])],
          'verifypassword': ['', [Validators.required]],

          }, { validator: this.passwordMatchValidator });

          passwordMatchValidator(g: FormGroup) {
          return g.get('password').value === g.get('verifypassword').value
          ? null : {'mismatch': true};
          }


          html



          <div *ngIf="form.invalid && form.errors['mismatch']">Password did not match</div>


          Sample example is here -https://stackblitz.com/edit/confirm-password-q3ngps




          Option 2 - Use a function to match the password.




          password-validator.ts



          export class PasswordValidation {

          static MatchPassword(AC: AbstractControl) {
          let password = AC.get('password').value;
          if(AC.get('confirmPassword').touched || AC.get('confirmPassword').dirty) {
          let verifyPassword = AC.get('confirmPassword').value;

          if(password != verifyPassword) {
          AC.get('confirmPassword').setErrors( {MatchPassword: true} )
          } else {
          return null
          }
          }
          }
          }


          Component ts



          this.form = this._fb.group({
          password: ['', Validators.required],
          confirmPassword: ['', Validators.required]
          }, {
          validator: PasswordValidation.MatchPassword
          });


          Working copy is here - https://stackblitz.com/edit/material-password-confirm-pnnd4t






          share|improve this answer


























          • it works but only when i press the submit button, i wuold like to check the validation as soon as the user touch the verifypassword field

            – Gelso77
            Nov 13 '18 at 11:35











          • I think you had put the condition in html when to show the error. Share your html.

            – Sunil Singh
            Nov 13 '18 at 11:38











          • updated,many thank Sunil!

            – Gelso77
            Nov 13 '18 at 11:52











          • I don't see the error message in your given html.

            – Sunil Singh
            Nov 13 '18 at 11:55











          • just because i am using the css ng-valid, ng-invalid, you know the validation password if is differents must be invalid ...after that if is invalid i can add a message

            – Gelso77
            Nov 13 '18 at 12:10


















          0















          Option 1 - Validate the password and verifyPassword through FormGroup,




          Here is simple sample code for confirm password validation where you need to pass the validator to FormGroup which contains both the contols password and confirmPassword.



            this.form = this._fb.group({
          'user': ['', Validators.compose([Validators.required])],
          'password': ['', Validators.compose([Validators.required])],
          'verifypassword': ['', [Validators.required]],

          }, { validator: this.passwordMatchValidator });

          passwordMatchValidator(g: FormGroup) {
          return g.get('password').value === g.get('verifypassword').value
          ? null : {'mismatch': true};
          }


          html



          <div *ngIf="form.invalid && form.errors['mismatch']">Password did not match</div>


          Sample example is here -https://stackblitz.com/edit/confirm-password-q3ngps




          Option 2 - Use a function to match the password.




          password-validator.ts



          export class PasswordValidation {

          static MatchPassword(AC: AbstractControl) {
          let password = AC.get('password').value;
          if(AC.get('confirmPassword').touched || AC.get('confirmPassword').dirty) {
          let verifyPassword = AC.get('confirmPassword').value;

          if(password != verifyPassword) {
          AC.get('confirmPassword').setErrors( {MatchPassword: true} )
          } else {
          return null
          }
          }
          }
          }


          Component ts



          this.form = this._fb.group({
          password: ['', Validators.required],
          confirmPassword: ['', Validators.required]
          }, {
          validator: PasswordValidation.MatchPassword
          });


          Working copy is here - https://stackblitz.com/edit/material-password-confirm-pnnd4t






          share|improve this answer


























          • it works but only when i press the submit button, i wuold like to check the validation as soon as the user touch the verifypassword field

            – Gelso77
            Nov 13 '18 at 11:35











          • I think you had put the condition in html when to show the error. Share your html.

            – Sunil Singh
            Nov 13 '18 at 11:38











          • updated,many thank Sunil!

            – Gelso77
            Nov 13 '18 at 11:52











          • I don't see the error message in your given html.

            – Sunil Singh
            Nov 13 '18 at 11:55











          • just because i am using the css ng-valid, ng-invalid, you know the validation password if is differents must be invalid ...after that if is invalid i can add a message

            – Gelso77
            Nov 13 '18 at 12:10
















          0












          0








          0








          Option 1 - Validate the password and verifyPassword through FormGroup,




          Here is simple sample code for confirm password validation where you need to pass the validator to FormGroup which contains both the contols password and confirmPassword.



            this.form = this._fb.group({
          'user': ['', Validators.compose([Validators.required])],
          'password': ['', Validators.compose([Validators.required])],
          'verifypassword': ['', [Validators.required]],

          }, { validator: this.passwordMatchValidator });

          passwordMatchValidator(g: FormGroup) {
          return g.get('password').value === g.get('verifypassword').value
          ? null : {'mismatch': true};
          }


          html



          <div *ngIf="form.invalid && form.errors['mismatch']">Password did not match</div>


          Sample example is here -https://stackblitz.com/edit/confirm-password-q3ngps




          Option 2 - Use a function to match the password.




          password-validator.ts



          export class PasswordValidation {

          static MatchPassword(AC: AbstractControl) {
          let password = AC.get('password').value;
          if(AC.get('confirmPassword').touched || AC.get('confirmPassword').dirty) {
          let verifyPassword = AC.get('confirmPassword').value;

          if(password != verifyPassword) {
          AC.get('confirmPassword').setErrors( {MatchPassword: true} )
          } else {
          return null
          }
          }
          }
          }


          Component ts



          this.form = this._fb.group({
          password: ['', Validators.required],
          confirmPassword: ['', Validators.required]
          }, {
          validator: PasswordValidation.MatchPassword
          });


          Working copy is here - https://stackblitz.com/edit/material-password-confirm-pnnd4t






          share|improve this answer
















          Option 1 - Validate the password and verifyPassword through FormGroup,




          Here is simple sample code for confirm password validation where you need to pass the validator to FormGroup which contains both the contols password and confirmPassword.



            this.form = this._fb.group({
          'user': ['', Validators.compose([Validators.required])],
          'password': ['', Validators.compose([Validators.required])],
          'verifypassword': ['', [Validators.required]],

          }, { validator: this.passwordMatchValidator });

          passwordMatchValidator(g: FormGroup) {
          return g.get('password').value === g.get('verifypassword').value
          ? null : {'mismatch': true};
          }


          html



          <div *ngIf="form.invalid && form.errors['mismatch']">Password did not match</div>


          Sample example is here -https://stackblitz.com/edit/confirm-password-q3ngps




          Option 2 - Use a function to match the password.




          password-validator.ts



          export class PasswordValidation {

          static MatchPassword(AC: AbstractControl) {
          let password = AC.get('password').value;
          if(AC.get('confirmPassword').touched || AC.get('confirmPassword').dirty) {
          let verifyPassword = AC.get('confirmPassword').value;

          if(password != verifyPassword) {
          AC.get('confirmPassword').setErrors( {MatchPassword: true} )
          } else {
          return null
          }
          }
          }
          }


          Component ts



          this.form = this._fb.group({
          password: ['', Validators.required],
          confirmPassword: ['', Validators.required]
          }, {
          validator: PasswordValidation.MatchPassword
          });


          Working copy is here - https://stackblitz.com/edit/material-password-confirm-pnnd4t







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 '18 at 13:48

























          answered Nov 13 '18 at 11:17









          Sunil SinghSunil Singh

          6,1572626




          6,1572626













          • it works but only when i press the submit button, i wuold like to check the validation as soon as the user touch the verifypassword field

            – Gelso77
            Nov 13 '18 at 11:35











          • I think you had put the condition in html when to show the error. Share your html.

            – Sunil Singh
            Nov 13 '18 at 11:38











          • updated,many thank Sunil!

            – Gelso77
            Nov 13 '18 at 11:52











          • I don't see the error message in your given html.

            – Sunil Singh
            Nov 13 '18 at 11:55











          • just because i am using the css ng-valid, ng-invalid, you know the validation password if is differents must be invalid ...after that if is invalid i can add a message

            – Gelso77
            Nov 13 '18 at 12:10





















          • it works but only when i press the submit button, i wuold like to check the validation as soon as the user touch the verifypassword field

            – Gelso77
            Nov 13 '18 at 11:35











          • I think you had put the condition in html when to show the error. Share your html.

            – Sunil Singh
            Nov 13 '18 at 11:38











          • updated,many thank Sunil!

            – Gelso77
            Nov 13 '18 at 11:52











          • I don't see the error message in your given html.

            – Sunil Singh
            Nov 13 '18 at 11:55











          • just because i am using the css ng-valid, ng-invalid, you know the validation password if is differents must be invalid ...after that if is invalid i can add a message

            – Gelso77
            Nov 13 '18 at 12:10



















          it works but only when i press the submit button, i wuold like to check the validation as soon as the user touch the verifypassword field

          – Gelso77
          Nov 13 '18 at 11:35





          it works but only when i press the submit button, i wuold like to check the validation as soon as the user touch the verifypassword field

          – Gelso77
          Nov 13 '18 at 11:35













          I think you had put the condition in html when to show the error. Share your html.

          – Sunil Singh
          Nov 13 '18 at 11:38





          I think you had put the condition in html when to show the error. Share your html.

          – Sunil Singh
          Nov 13 '18 at 11:38













          updated,many thank Sunil!

          – Gelso77
          Nov 13 '18 at 11:52





          updated,many thank Sunil!

          – Gelso77
          Nov 13 '18 at 11:52













          I don't see the error message in your given html.

          – Sunil Singh
          Nov 13 '18 at 11:55





          I don't see the error message in your given html.

          – Sunil Singh
          Nov 13 '18 at 11:55













          just because i am using the css ng-valid, ng-invalid, you know the validation password if is differents must be invalid ...after that if is invalid i can add a message

          – Gelso77
          Nov 13 '18 at 12:10







          just because i am using the css ng-valid, ng-invalid, you know the validation password if is differents must be invalid ...after that if is invalid i can add a message

          – Gelso77
          Nov 13 '18 at 12:10




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53279777%2fangular-custom-validation-with-parameter%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python