简体   繁体   中英

if array does not contain string

I'am making a user registration page, and I don't want any char's that does not match the array.

function create(){
var allowed = [
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9","0","_","-"];

var username = $("#username").val();

if (username == ""){
document.getElementById("usernameerror").style.color = "red";
document.getElementById("usernameerror").innerHTML = " Username cannot be blank.";
}else{

if (username.indexOf(allowed) != -1){
document.getElementById("usernameerror").style.color = "red";
document.getElementById("usernameerror").innerHTML = " No symbols.";
}else{
document.getElementById("usernameerror").style.color = "blue";
document.getElementById("usernameerror").innerHTML = " ✔";
}

}

}

I bet it's something simple.. (not sub string)

This is exactly the kind of problem that regular expressions are designed to solve. Try replacing this line:

if (username.indexOf(allowed) != -1){

...with this:

if (!/^[a-z0-9_-]*$/i.test(username)) {

Your requirements are very similar to the \\w metacharacter as well, which would let you alternatively use this for your regex:

/^[\w-]+$/

How about:

 if (username.match(/[^\\w-]/) !== null) { console.log('username has non-word characters...'); } 

See here for what \\w does: MDN Regular Expression .

Check this out:

if (/^[a-z0-9\-\_]+$/.test(username)) {
  document.getElementById("usernameerror").style.color = "red";
  document.getElementById("usernameerror").innerHTML = " No symbols.";
}else{
  document.getElementById("usernameerror").style.color = "blue";
  document.getElementById("usernameerror").innerHTML = " ✔";
}

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