javascriptregexecmascript-6onkeyupkey-events

String Replace with Regex Decimal Validation fails in Javascript


I tried to restrict the user input with string.replace using Regular expression. But it fails, its not allow to enter any character. Kindly see the following HTML Page.

<!DOCTYPE html>
<html>
<head>
	<title>Decimal Validation</title>
</head>
<body>
<p>A function is triggered when the user is pressing a key and on keyup in the input field.</p>

<input type="text" maxlength="9" onkeyup="myFunction(this)">

<script>

function myFunction(text) {
	if(text) {
    	text.value = text.value.replace(/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8})/g, '');
	}
}

</script>
</body>
</html>

I need to allow only the digits and precision (i.e., allow only one dot). If the user input is only a whole number then the length should be 9 or if the input is only decimal part then allow maximum 8 precision or if the mixture then allow decimal(9,5) - allow 4 digit and 5 precision.

The above said regular expression fails to validate, allow the char only digits and only one period.


Solution

  • A validation and a replacement are two different tasks, you need to test the field first and after to replace with something eventually. Example:

    function myFunction(text) {
        if( !/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8})$/.test(text.value) ) {
            text.value = ''; // or an other kind of replacement if you need something
                             // more precise
        }
    }
    

    Note that you can also rewrite the pattern like this:

    /^(?!\d*\.\d*\.)[\d.]{0,9}$/
    

    To keep characters at the beginning that validate the pattern you can use this replacement:

    text.value = text.value.replace(/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8}).*/, '$1');