Reputation: 169
I am working on a Binary2Decimal convertor app, where when the user enters other than 0s and 1s in input field, then while clicking on convert it should alert the user to enter valid binary number.
Below is my code:
const binary = document.querySelector('.decimalConvertor__binary--bin');
const decimal = document.querySelector('.decimalConvertor__decimal--dec');
const submit = document.querySelector('.decimalConvertor__submit--sub');
submit.addEventListener('click', e => {
const bin = binary.value;
if(bin !== '' && ' ') {
if(bin.length <=8) {
let dec = 0;
for (let i = bin.length-1; i >=0; i--) {
dec += parseInt(bin[i]) * Math.pow(2, bin.length - 1 - i);
}
decimal.value = dec
}else {
alert('enter less than 8 numbers')
}
}else {
alert('Please enter valid binary number')
}
});
Upvotes: 1
Views: 140
Reputation: 1763
try this, it uses regex to test whether the string contains numbers other than 1 and 0, if it does, then it shows the alert to enter a valid binary number:
var re = new RegExp("([23456789])");
submit.addEventListener('click', e => {
const bin = binary.value;
if(bin && !re.test(bin)) {
if(bin.length <=8) {
let dec = 0;
for (let i = bin.length-1; i >=0; i--) {
dec += parseInt(bin[i]) * Math.pow(2, bin.length - 1 - i);
}
decimal.value = dec
}else {
alert('enter less than 8 numbers')
}
}else {
alert('Please enter valid binary number')
}
});
Here's a website where you can create regexes and it'll show you their explanation: https://regexr.com/ . Enter the regex there for it's explanation!
Upvotes: 1
Reputation: 4330
You can use regex for this purpose: /^[0-1]*$/
will test for only 0 and 1. You can use regex.test(bin)
submit.addEventListener('click', e => {
regex = /^[0-1]*$/;
const bin = binary.value;
if(bin && regex.test(bin)) {
if(bin.length <= 8) {
let dec = 0;
for (let i = bin.length-1; i >=0; i--) {
dec += parseInt(bin[i]) * Math.pow(2, bin.length - 1 - i);
}
decimal.value = dec
}
else {
alert('enter less than 8 numbers')
}
}
else {
alert('Please enter valid binary number')
}
});
PS: There is one more bug in your code. Inside the if clause you have written bin !== '' && ' '
which is always true when bin !== ''
, which means && ' '
is redundent.
Upvotes: 1