1

I have this validate function component how I can use It to return callback funcion?

the first file only for check validity

export function checkValidity(value, rules, shouldValidat) {
   let isValid = true;

    return isValid;
}

the second file caller

import { checkValidity } from "../UI/CheckValidity";
let res = checkValidity(vlaue, validationRules, shouldValidat);

callback = () =>{
   alert("call back function is done");
} 

how I can call the callback function from the first file using react js?

1
  • pass callback as argument to checkvalidity and call it right before return Commented Nov 26, 2018 at 10:49

3 Answers 3

1

You need to have a callback in checkValidity function.

So you need to add callback as argument in checkValidity(value, rules, shouldValidat, callback) and then simply do:

export function checkValidity(value, rules, shouldValidat, callback) {
   let isValid = true;
   /*do your validation here and if it's okay then call callback*/
   callback();
   return isValid;
}
Sign up to request clarification or add additional context in comments.

2 Comments

maybe return the value in the callback as well ? callback(value)
let res = checkValidity(vlaue, validationRules, shouldValidat, this.callback);
1

You should write a function which is like ;

callback(email) {
const re = ..... => it should be validation rule 
if(re.test) {
return email;
}
return false;

and when you call function in other function you should give your email or other params for function param .

Comments

0

Two callback examples:

  1. Callback when something is true callback(isValid)
  2. Callback to deal with false (if needed) errorcallback(isValid)

    export const checkValidity = (value, rules, shouldValidate, callback, errorcallback) => {
        let isValid = true; // hardcoded
        isValid ? callback(isValid) : errorcallback(isValid)
        return isValid;
    }
    

How to invoke

Pass your functions as arguments 4 & 5, in this case, callback and errorcallback

val denotes a parameter passed back from the callback. in our example above were passing isValid which we are now calling val from where checkValidity() is invoked.

import { checkValidity } from "../UI/CheckValidity";
let res = checkValidity(value, validationRules, shouldValidate);

checkValidity(
    value,
    rules,
    shouldValidate,
    (val) => {console.log('callback() if true!! ' + val )},
    (val) => {console.log('errorcallback() if false!!' + val}
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.