Home > Software design >  How to Validation value with array data?
How to Validation value with array data?

Time:11-10

This my HTML Code

<html>
  <body>
    <h2>Validation Array</h2>
    <input id="search" onblur="read()">

    <label id="creat"></label>

  </body>
</html>

And this my Javascript

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var search = document.getElementById("search").value;

function read() {
  if(search != fruits){
      document.getElementById("creat").innerHTML = "Error";
  } else {
      document.getElementById("creat").innerHTML = "Valid";
  }
}

i want to validation write "Valid" if value = in array. thanks

CodePudding user response:

There are a couple problems, you need to get the search value within the function, otherwise it will be the first value no matter which changes are made. Then, you can use Array.includes to check if the value is in the array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];

function read() {
  var search = document.getElementById("search").value;
  if(!fruits.includes(search)) {
      document.getElementById("creat").innerHTML = "Error";
  } else {
      document.getElementById("creat").innerHTML = "Valid";
  }
}
<html>
  <body>
    <h2>Validation Array</h2>
    <input id="search" onblur="read()">

    <label id="creat"></label>

  </body>
</html>

CodePudding user response:

You can use the .includes() method:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var search = document.getElementById("search").value;

function read() {
  if(!fruits.includes(search)){
      document.getElementById("creat").innerHTML = "Error";
  } else {
      document.getElementById("creat").innerHTML = "Valid";
  }
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

CodePudding user response:

function read() {
  let inArray = fruits.includes(search);
  if(inArray){
      document.getElementById("creat").innerHTML = "Error";
  } else {
      document.getElementById("creat").innerHTML = "Valid";
  }
}

CodePudding user response:

You can either loop through all elements and check of the current element is equal to the string entered in "search". Or you can just use the .includes function ;)

  • Related