-1

I want to validate, but when I enter a number or a string in any case, the data type shows me a string and I can not validate correctly, please help me

    function Validator() {
        const x = document.getElementById("fname").value;
        const a = typeof x === "string" && x.length >= 1;
         console.log(typeof x);
        if (a) {
            console.log("type string");
        } else {
            console.log("other type");
        };
    }
  <input id="fname">
  <input type="submit" onclick="Validator()">
Amir93
  • 5
  • 5

3 Answers3

2

Values from input fiedls are only Strings. So you have to parse it.

    const x = document.getElementById("fname").value;
    if (x.length >= 1) {
      if (Number.isNaN(x) == false) {
        console.log("Numeric type");
        //Using parse methods for different numbers)
      } else if (x.length>0) {
        console.log("String type");
      }
     }

For more details: https://www.w3schools.com/jsref/jsref_isnan.asp

Reporter
  • 3,897
  • 5
  • 33
  • 47
1

You can do it like this, use the Number.isNaN() function to check if something is not a number. Pass parseInt(x) to Number.isNaN(), which will try and convert x to a number. If it cannot convert it, it will return NaN.

function Validator() {
    const x = document.getElementById("fname").value;
    const isNaN = Number.isNaN(parseInt(x));
    if (isNaN) {
        console.log("type string");
    } else {
        console.log("number type");
    };
}
<input id="fname">
<input type="submit" onclick="Validator()">
tdranv
  • 1,140
  • 11
  • 38
0

The value of an input is always a string. For example, when you enter 1, the actual value is not number 3, its the string "3". You can use isNan() function as stated in above examples.

Read more on validating numbers in this post - (Built-in) way in JavaScript to check if a string is a valid number