简体   繁体   中英

Check for occurrence of at least one non numeric value in input string

I have tried many regex but it still does not work. Please tell where I might be wrong:

  1. I take input from user (expecting it will be only number).
  2. myArray = str.replace(/\\s+/g,"").split(""); //remove any spaces if present & split each character
  3. if(/^[0-9]/.test(myArray)) console.log("Make sure you enter all number"); else console.log("Successful");

Output if given following input (str) :

  • 455e5 7523 1455 -> "Make sure you enter all number"

  • 4555 2375 2358 -> "Make sure you enter all number" instead of "Successful"

I have tried /^[0-9]+/ , /^\\d+$/ , /(^\\d)*/ and many similar expression. It did not help me out. Is it because of split() because i have remove it and also tried.

Use \\D to match non numeric character

if(/\D/.test(myArray))
    console.log("Make sure you enter all number");
else
    console.log("Successful");

DEMO :

 function test(myArray) { if (/\\D/.test(myArray.replace(/\\s+/g,""))) console.log("Make sure you enter all number"); else console.log("Successful"); } 
 <input oninput="test(this.value)" /> 

Or you can use [^\\d\\s] for matching character except digit and space

 function test(myArray) { if (/[^\\d\\s]/.test(myArray)) console.log("Make sure you enter all number"); else console.log("Successful"); } 
 <input oninput="test(this.value)" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM