<html>
<head>
  <title>Contoh Validasi Saldo</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <form id="form" onsubmit="return validasiForm()">
    <input type="hidden" name="tsaldo" value="50000" id="tsaldoHidden">
    <label>Saldo: Rp. <span id="tsaldo">50.000</span></label><br>
    <label>Penarikan:</label>
    <input type="text" name="ttarik" id="ttarik" required onkeypress="return hanyaAngkaDanTitik(event)" onkeyup="formatRupiah(this)"><br>
    <input type="hidden" name="ttarikHidden" id="ttarikHidden">
    <button type="submit">Submit</button>
  </form>

  <script>
    function hanyaAngkaDanTitik(event) {
      var charCode = event.which;
      if ((charCode >= 48 && charCode <= 57) || charCode == 46) {
        return true;
      } else {
        return false;
      }
    }

    function formatRupiah(obj) {
      var nilai = obj.value.replace(/\./g, '');
      obj.value = addCommas(nilai);
      document.getElementById('ttarikHidden').value = nilai;
    }

    function addCommas(nStr) {
      nStr += '';
      x = nStr.split('.');
      x1 = x[0];
      x2 = x.length > 1 ? '.' + x[1] : '';
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
      }
      return x1 + x2;
    }

    function validasiForm() {
      var saldo = parseInt(document.getElementById('tsaldoHidden').value);
      var tarik = parseInt(document.getElementById('ttarikHidden').value);
      if (isNaN(tarik)) {
        alert('Input tidak valid');
        return false;
      }
      if (tarik > saldo) {
        alert('SALDO KURANG');
        return false;
      }
      return true;
    }
  </script>
</body>
</html>