Jim Mattis, U.S. secretary of defense, testifies during a Senate Armed Forces Committee hearing on Tuesday. Mattis said that he believed it was in the national security interests of the United States to stay in the Iran nuclear deal. (Zach Gibson/Bloomberg)

The nation's top military leaders stated unequivocally on Tuesday that they believe the United States should stay in the Iran nuclear deal, staking out a position at odds with President Trump's only days before he decides whether to certify that Tehran is in compliance with the deal.

When asked by Sen. Angus King (I-Maine) if he believed "it's in our national security interest at the present time to remain" in the nuclear pact, Defense Secretary Jim Mattis said, "Yes, senator, I do."

Mattis and Chairman of the Joint Chiefs of Staff Gen. Joseph F. Dunford Jr. spoke during hearings before the Senate and House armed services committees that were primarily focused on the state of the war in Afghanistan. But at each hearing, the top Pentagon officials faced questions about the Iran nuclear pact, which is hitting critical deadline.

Trump must decide by Oct. 15 if he will certify that Tehran is in compliance with the terms of the multilateral pact under which Iran agreed to give up its nuclear ambitions in exchange for a withdrawal of nuclear sanctions. Since his presidential campaign, Trump has spared no kind words for Iran or the nuclear pact, which he called "an embarrassment" during a speech to the United Nations General Assembly last month.

Should the president decline to certify the deal, the decision of whether to adhere to or rupture the pact would belong to Congress, as lawmakers would have to decide whether to reimpose sanctions. Even the Republicans are divided over what they think is the most prudent course of action.

But Mattis and Dunford were unanimous in their support for the deal.

Even if Trump declines to certify Iran's compliance, Mattis told the lawmakers, Congress did not have to rip up the nuclear deal.

"We're talking about the law that is passed up here, where we have to certify, plus the agreement … they're two different pieces," Mattis told Sen. Kirsten Gillibrand (D-N.Y.). "You can talk about the conditions under one of those and not walk away from the other one of those."

Later, in testimony before the House Armed Services Committee, the defense secretary said, "Overall, our intelligence community believes that they [Iran] have been compliant, and the IAEA also says so." Mattis was referring to the International Atomic Energy Agency, the United Nations watchdog that's monitoring Iran's nuclear activity.

Dunford repeated his testimony from last week, saying "that Iran is not in material breach of the agreement." He told Gillibrand, "I do believe the agreement to date has delayed the development of a nuclear capability by Iran.

Dan Lamothe contributed to this report