Hi all,

I have an input box that should only contain decimal point numbers (including negative values), but I'm not sure how to remove invalid characters and replace it with something that is valid (i.e. the value e3.45 should be replaced with 3.45). If all the characters in the textbox are not valid, then a zero should be input as the value.

Working with regular expressions is not my strong point, so any help would be greatly appreciated, even if it's just helping me onto the right track.

Thanks in advance

Dani AI

Generated

Good start and thanks to for the validation idea. The regex shown earlier is useful for testing, but the task here is sanitizing (removing bad characters) and normalizing input so values like e3.45 become 3.45, -.5 becomes -0.5, and completely invalid input becomes 0. The snippet below is a compact, reliable sanitizer that preserves a single leading minus, keeps only digits and one decimal point, and falls back to "0" when nothing valid remains.

function sanitizeNumber(input) {
  var s = String(input || '');
  var trimmed = s.trim();
  var isNegative = trimmed.charAt(0) === '-';

  // strip everything except digits and dot
  s = s.replace(/[^0-9.]/g, '');

  // keep only the first dot
  var parts = s.split('.');
  s = parts.shift() + (parts.length ? '.' + parts.join('') : '');

  // empty or just a dot -> zero
  if (s === '' || s === '.') return '0';

  // leading dot -> prefix 0
  if (s.charAt(0) === '.') s = '0' + s;

  // apply leading minus only if there is a non-zero value
  if (isNegative && s !== '0') s = '-' + s;

  return s;
}

// example binding (cleanup on blur)
document.getElementById('txt1').addEventListener('blur', function () {
  this.value = sanitizeNumber(this.value);
});

Notes and tips: the function treats a minus only when it appears as the first non-space character (safer than rescuing interior minuses). For calculations, convert the sanitized string with parseFloat() and fallback to 0 if isNaN. Prefer sanitizing on blur or on submit rather than trying to block every keystroke (live filtering can break IME/paste/caret position). For locales using comma as the decimal mark, adapt the allowed character set accordingly.

<html>
<head>
<script lang='javascript'>
var isNumeric  = /^(\d*)(\.?)(\d*)$/;

function checknum()
{
     if (!isNumeric.test(document.frm.txt1.value))
     {
	 alert( 'Not a valid number');
	 return false;
     }
     else
     {
        alert( 'Number Accepted');
	return false;
     }
}
</script>
</head>
<body>
<form name=frm id=frm action='#' method=post>
<input type=text name=txt1 id=txt1>
<input type=button name=btn1 id=btn1 value=check onclick='javascript:checknum()'>
</form>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.