javascript – Form data validation does not work correctly JS

Question:

There is a code:

const button = document.querySelector('.final');
const paragraph = document.querySelector('.answer');
const kk = document.querySelector('.k').value;
const nn = document.querySelector('.n').value;

const summ = () => {
  const kk = document.querySelector('.k').value;
  const nn = document.querySelector('.n').value;
  const multiplication = k * n;
  return multiplication;
}

button.addEventListener('click', () => {
  if (typeof(kk) !== 'number' || typeof(nn) !== 'number' || kk < 0 || nn < 0) {
    paragraph.innerHTML = 'Enter valid numbers';
  } else {
    paragraph.innerHTML = summ();
  }
});
<input type="text" class="k">
<input type="text" class="n">
<input type="submit" class="final">
<p class="answer">

It fits the result, but ignores my if-else check for тип данных and input > 0 .

Where did I go wrong?

Answer:

const kk = document.querySelector('.k').value;
const nn = document.querySelector('.n').value;

You get these values ​​once, during the script launch (when the inputs are still empty, both will be "" ) – each time they are checked. Both are strings (even if the HTML initially contains numeric values), which is why they pass the comparison !== "number" (a string is not a number).

Why does the function multiply, but is it called "sum"?

const button = document.querySelector('.button');
const answer = document.querySelector('.answer');
const k = document.querySelector('.k');
const n = document.querySelector('.n');

button.addEventListener('click', function() {
  answer.textContent = validate_n_mul(k.value, n.value);
  
  /***/                 
  function validate_n_mul(str_1, str_2) {
    if (
      !str_1 || !str_2 ||     // пустая строка
      isNaN(str_1 + str_2) || // где-то ввели не число
      str_1 < 0 || str_2 < 0  // меньше нуля
    ) return 'Enter valid numbers';

    return str_1 * str_2;
  }
});
<input type="text" class="k">
<input type="text" class="n">
<input type="submit" class="button">
<p class="answer">

str_1 < 0 – when comparing a string with a number, the string will also be implicitly converted to a numeric type. But if both are strings, "11" < "9" will return true. You need to be careful with this (turn them into numbers beforehand).

Scroll to Top