Caution: Translations of Quran and Ḥadīth may lead to possible misapplications and misinterpretations. This site is intended for students of sacred knowledge that are proficient in comprehending classical Arabic and have a strong foundation in Islamic sciences. Also note that religious injunctions rely on several aspects beyond what one may glean through reading individual aḥādīth.
quran:12:24

And she certainly determined ˹to seduce˺ him, and he would have inclined to her had he not seen the proof of his Lord. And thus ˹it was˺ that We should avert from him evil and immorality. Indeed, he was of Our chosen servants.  

And she certainly desired him, she sought sexual intercourse with him, and he would have desired her ˹too˺, he would have sought the same, had it not been that he saw the proof of his Lord: Ibn ‘Abbās said, ‘Jacob was made to appear before him, and he struck his ˹Joseph’s˺ breast, whereupon his ˹sexual˺ desire withdrew ˹from his body˺ through his fingernails (the response to lawlā, ‘had it not been’, has been omitted: ˹understood to be˺ la-jāma‘ahā, ‘he would have lain with her’). So it was, that We made him see the proof, that We might ward off from him evil, betrayal, and lewdness, ˹the act of˺ fornication. Truly he was of Our devoted servants, in terms of obedience (mukhlisīn: a variant reading has mukhlasīn, in other words, ‘chosen/purified ˹servants˺’).
القرآن:١٢:٢٤

وَلَقَدْ هَمَّتْ بِهِ ۖ وَهَمَّ بِهَا لَوْلَا أَنْ رَأَىٰ بُرْهَانَ رَبِّهِ ۚ كَذَٰلِكَ لِنَصْرِفَ عَنْهُ السُّوءَ وَالْفَحْشَاءَ ۚ إِنَّهُ مِنْ عِبَادِنَا الْمُخْلَصِينَ  

{ولقد همَّت به} قصدت منه الجماع {وهمَّ بها} قصد ذلك {لولا أن رأى برهان ربه} قال ابن عباس مَثُل له يعقوب فضرب صدره فخرجت شهوته من أنامله وجواب لولا لجامعها {كذلك} أريناه البرهان {لنصرف عنه السوء} الخيانة {والفحشاء} الزنا {إنه من عبادنا المخلصين} في الطاعة وفي قراءة بفتح اللام أي المختارين.