0

im trying reactjs and i got an undefined and i dont kow why. The code is really simple but maybe i didnt get something ?!

  isMailValid(mail) {
    const valid_mail = RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    console.log("res => " + valid_mail.test(mail));
    return valid_mail.test(mail);
  }

  isMailOk() {
    var res = this.isMailValid(this.state.mail)
    if (res === true)
      return (<p class="false">invalid mail</p>);
    return (<p class="good">Mail Ok</p>); 
  }

I got 'isMailValid' is not defined no-undef. Thx for help

4
  • Can you post your whole class? Commented Dec 18, 2018 at 19:50
  • 1
    valid_mail is a string. it doesn't have test. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 18, 2018 at 19:50
  • To fix your code, it needs to be const valid_mail = RegExp("[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"); Commented Dec 18, 2018 at 19:56
  • thanks it solves a problem but i cant get what i want. there is no message under the input. (I edit the code) Commented Dec 18, 2018 at 19:59

1 Answer 1

1

The function is undefined because it is not in the same scope as the function calling it. To access it you'll have to prefix the call with this. to tell React where to find the function.

isMailOk() {
    if (this.isMailValid(this.state.mail) === true)
      return (<p class="false">Mail invalid</p>);
    return (<p class="good">Mail Ok</p>); 
  }

You'll also have to bind your custom function to this. You can do that by placing this.isMailOk = this.isMailOk.bind(this); in the constructor. You'll have to do that with both of your custom functions. Functions such as render don't require being bound to this because they are inherited when you extend your class from React.Component. You can read more about binding to this in the docs.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd encourage reading through the docs for binding functions to the class. You can also do it through the arrow syntax (=>). If you're using create-react-app, the support is out of the box. You don't have to bind in the constructor if your functions use the arrow syntax.

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.