Reputation: 1332
I want to check if input text (amount) is between 1-100 or not but regex test not working.
here is my JS code
<script type="text/javascript" >
console.log(document.getElementById("amount").value); // 222
var regex = /^(100)|[1-9]\d?$/;
if(regex.test(document.getElementById("amount").value))
{
alert('validated')
}
else
alert('error')
</script>
Upvotes: 1
Views: 609
Reputation: 1
<html>
<head>
<script>
function validateValue()
{
var amount = document.getElementById('testId').value;
if((isNaN(amount ))){
document.getElementById("errorId").style.display= "";
}
else
{
if(amount>100){
document.getElementById("errorId").style.display= "";
}
else
{
document.getElementById("errorId").style.display= "none";
}
}
}
</script>
</head>
<body>
Enter 1 to 100:<input type="text" onkeyup="validateValue()" id="testId"/>
<span id="errorId" style="color:red;display:none"> Not a valid amount</span>
</body>
</html>
Upvotes: 0
Reputation: 92854
It would be enough to use parseInt()
function or Number
constructor to perform such a simple validation:
<script type="text/javascript" >
var amount = Number(document.getElementById("amount").value); // 222
alert ((amount > 0 && amount <= 100)? 'Valid' : 'Invalid');
</script>
Upvotes: 1
Reputation: 87203
DOMContentLoaded
event callbackCode:
document.addEventListener('DOMContentLoaded', function () {
// Get the value & convert it into Number
var value = parseInt(document.getElementById('amount').value, 10);
// Value between 0 & 100
if (value > 0 && value <= 100) {
alert('Valid');
} else {
alert('Error');
}
});
Upvotes: 4
Reputation: 6742
If you really want to use regex, this should work:
/^100$|^[1-9]\d?$/
It doesn't allow eg 09
, but maybe that's OK.
Upvotes: 0