How to trigger validation on reactive form through input decorator?











up vote
0
down vote

favorite












I have a validation directive that takes an input from a parent component. The validation is passed only when the input is true. So whenever an input changes, I don't know how to trigger validation method in the directive



I have a sample working code on stackblitz for the purpose of demonstrating the issue



//As you can see the appRouteValidator is passing an input randomNumber

<input type="random" appRouteValidator [randomOption]="randomNumber"
formControlName="random" class="form-control"/>


The validate method here is I want to call on every time the input changes,



export class DemoValidatorDirective {
@Input() randomOption: Boolean;


ngOnChanges(changes: SimpleChanges) {
if (changes.randomOption.currentValue) {
//---------------------------------> Should trigger validate method
}
}
constructor() { }
// This should be called when it receives an input
validate(control: AbstractControl): { [key: string]: any; } {
console.log('validation method called');
if (control && (control.value !== null || control.value !== undefined)) {
const randomField = control.value;
if (!randomField || !this.randomOption) {
return {
'validationError': 'invalid random number'
};
}
}
return null;
}
}









share|improve this question






















  • input is true means?
    – Ajay Ojha
    Nov 10 at 13:15










  • @Input() randomOption: Boolean; it receives a boolean.
    – anonymous
    Nov 10 at 13:16










  • Ok, please correct me if I am wrong, based on your randomOption value you want to validate the 'random' control? if the value is true then it should validate otherwise not.
    – Ajay Ojha
    Nov 10 at 13:36










  • Question is I want to trigger the validate method when the directive receives the input.
    – anonymous
    Nov 10 at 14:03















up vote
0
down vote

favorite












I have a validation directive that takes an input from a parent component. The validation is passed only when the input is true. So whenever an input changes, I don't know how to trigger validation method in the directive



I have a sample working code on stackblitz for the purpose of demonstrating the issue



//As you can see the appRouteValidator is passing an input randomNumber

<input type="random" appRouteValidator [randomOption]="randomNumber"
formControlName="random" class="form-control"/>


The validate method here is I want to call on every time the input changes,



export class DemoValidatorDirective {
@Input() randomOption: Boolean;


ngOnChanges(changes: SimpleChanges) {
if (changes.randomOption.currentValue) {
//---------------------------------> Should trigger validate method
}
}
constructor() { }
// This should be called when it receives an input
validate(control: AbstractControl): { [key: string]: any; } {
console.log('validation method called');
if (control && (control.value !== null || control.value !== undefined)) {
const randomField = control.value;
if (!randomField || !this.randomOption) {
return {
'validationError': 'invalid random number'
};
}
}
return null;
}
}









share|improve this question






















  • input is true means?
    – Ajay Ojha
    Nov 10 at 13:15










  • @Input() randomOption: Boolean; it receives a boolean.
    – anonymous
    Nov 10 at 13:16










  • Ok, please correct me if I am wrong, based on your randomOption value you want to validate the 'random' control? if the value is true then it should validate otherwise not.
    – Ajay Ojha
    Nov 10 at 13:36










  • Question is I want to trigger the validate method when the directive receives the input.
    – anonymous
    Nov 10 at 14:03













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a validation directive that takes an input from a parent component. The validation is passed only when the input is true. So whenever an input changes, I don't know how to trigger validation method in the directive



I have a sample working code on stackblitz for the purpose of demonstrating the issue



//As you can see the appRouteValidator is passing an input randomNumber

<input type="random" appRouteValidator [randomOption]="randomNumber"
formControlName="random" class="form-control"/>


The validate method here is I want to call on every time the input changes,



export class DemoValidatorDirective {
@Input() randomOption: Boolean;


ngOnChanges(changes: SimpleChanges) {
if (changes.randomOption.currentValue) {
//---------------------------------> Should trigger validate method
}
}
constructor() { }
// This should be called when it receives an input
validate(control: AbstractControl): { [key: string]: any; } {
console.log('validation method called');
if (control && (control.value !== null || control.value !== undefined)) {
const randomField = control.value;
if (!randomField || !this.randomOption) {
return {
'validationError': 'invalid random number'
};
}
}
return null;
}
}









share|improve this question













I have a validation directive that takes an input from a parent component. The validation is passed only when the input is true. So whenever an input changes, I don't know how to trigger validation method in the directive



I have a sample working code on stackblitz for the purpose of demonstrating the issue



//As you can see the appRouteValidator is passing an input randomNumber

<input type="random" appRouteValidator [randomOption]="randomNumber"
formControlName="random" class="form-control"/>


The validate method here is I want to call on every time the input changes,



export class DemoValidatorDirective {
@Input() randomOption: Boolean;


ngOnChanges(changes: SimpleChanges) {
if (changes.randomOption.currentValue) {
//---------------------------------> Should trigger validate method
}
}
constructor() { }
// This should be called when it receives an input
validate(control: AbstractControl): { [key: string]: any; } {
console.log('validation method called');
if (control && (control.value !== null || control.value !== undefined)) {
const randomField = control.value;
if (!randomField || !this.randomOption) {
return {
'validationError': 'invalid random number'
};
}
}
return null;
}
}






angular angular-reactive-forms






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 12:56









anonymous

185115




185115












  • input is true means?
    – Ajay Ojha
    Nov 10 at 13:15










  • @Input() randomOption: Boolean; it receives a boolean.
    – anonymous
    Nov 10 at 13:16










  • Ok, please correct me if I am wrong, based on your randomOption value you want to validate the 'random' control? if the value is true then it should validate otherwise not.
    – Ajay Ojha
    Nov 10 at 13:36










  • Question is I want to trigger the validate method when the directive receives the input.
    – anonymous
    Nov 10 at 14:03


















  • input is true means?
    – Ajay Ojha
    Nov 10 at 13:15










  • @Input() randomOption: Boolean; it receives a boolean.
    – anonymous
    Nov 10 at 13:16










  • Ok, please correct me if I am wrong, based on your randomOption value you want to validate the 'random' control? if the value is true then it should validate otherwise not.
    – Ajay Ojha
    Nov 10 at 13:36










  • Question is I want to trigger the validate method when the directive receives the input.
    – anonymous
    Nov 10 at 14:03
















input is true means?
– Ajay Ojha
Nov 10 at 13:15




input is true means?
– Ajay Ojha
Nov 10 at 13:15












@Input() randomOption: Boolean; it receives a boolean.
– anonymous
Nov 10 at 13:16




@Input() randomOption: Boolean; it receives a boolean.
– anonymous
Nov 10 at 13:16












Ok, please correct me if I am wrong, based on your randomOption value you want to validate the 'random' control? if the value is true then it should validate otherwise not.
– Ajay Ojha
Nov 10 at 13:36




Ok, please correct me if I am wrong, based on your randomOption value you want to validate the 'random' control? if the value is true then it should validate otherwise not.
– Ajay Ojha
Nov 10 at 13:36












Question is I want to trigger the validate method when the directive receives the input.
– anonymous
Nov 10 at 14:03




Question is I want to trigger the validate method when the directive receives the input.
– anonymous
Nov 10 at 14:03












1 Answer
1






active

oldest

votes

















up vote
0
down vote













for manually calling validation method of Respective FormControl, you need call the AbstractControl class method of 'updateValueAndValidity' based on your validation rules.



I have added two lines in the generateRandomNumber method, here is the code:



generateRandomNumber() {
let randomNumber: any = Math.floor(Math.random() * 2) + 1;
this.randomNumber = randomNumber % 2 === 0;
if(this.randomNumber)
this.registerForm.controls.random.updateValueAndValidity();
console.log('random number', this.randomNumber);
}




Please refer the working example on stackblitz



Please let me know if you have any question.






share|improve this answer





















    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',
    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%2f53239178%2fhow-to-trigger-validation-on-reactive-form-through-input-decorator%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    for manually calling validation method of Respective FormControl, you need call the AbstractControl class method of 'updateValueAndValidity' based on your validation rules.



    I have added two lines in the generateRandomNumber method, here is the code:



    generateRandomNumber() {
    let randomNumber: any = Math.floor(Math.random() * 2) + 1;
    this.randomNumber = randomNumber % 2 === 0;
    if(this.randomNumber)
    this.registerForm.controls.random.updateValueAndValidity();
    console.log('random number', this.randomNumber);
    }




    Please refer the working example on stackblitz



    Please let me know if you have any question.






    share|improve this answer

























      up vote
      0
      down vote













      for manually calling validation method of Respective FormControl, you need call the AbstractControl class method of 'updateValueAndValidity' based on your validation rules.



      I have added two lines in the generateRandomNumber method, here is the code:



      generateRandomNumber() {
      let randomNumber: any = Math.floor(Math.random() * 2) + 1;
      this.randomNumber = randomNumber % 2 === 0;
      if(this.randomNumber)
      this.registerForm.controls.random.updateValueAndValidity();
      console.log('random number', this.randomNumber);
      }




      Please refer the working example on stackblitz



      Please let me know if you have any question.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        for manually calling validation method of Respective FormControl, you need call the AbstractControl class method of 'updateValueAndValidity' based on your validation rules.



        I have added two lines in the generateRandomNumber method, here is the code:



        generateRandomNumber() {
        let randomNumber: any = Math.floor(Math.random() * 2) + 1;
        this.randomNumber = randomNumber % 2 === 0;
        if(this.randomNumber)
        this.registerForm.controls.random.updateValueAndValidity();
        console.log('random number', this.randomNumber);
        }




        Please refer the working example on stackblitz



        Please let me know if you have any question.






        share|improve this answer












        for manually calling validation method of Respective FormControl, you need call the AbstractControl class method of 'updateValueAndValidity' based on your validation rules.



        I have added two lines in the generateRandomNumber method, here is the code:



        generateRandomNumber() {
        let randomNumber: any = Math.floor(Math.random() * 2) + 1;
        this.randomNumber = randomNumber % 2 === 0;
        if(this.randomNumber)
        this.registerForm.controls.random.updateValueAndValidity();
        console.log('random number', this.randomNumber);
        }




        Please refer the working example on stackblitz



        Please let me know if you have any question.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 14:30









        Ajay Ojha

        93027




        93027






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239178%2fhow-to-trigger-validation-on-reactive-form-through-input-decorator%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            Full-time equivalent

            さくらももこ

            13 indicted, 8 arrested in Calif. drug cartel investigation