2017-01-05 30 views
-1

私はユーザー登録ページを作成していますが、配列に一致しないcharは必要ありません。配列に文字列が含まれていない場合

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 = " ✔"; 
} 

} 

} 

私はそれは単純なもの..(ないサブ文字列)

+4

Checkout JS [正規表現](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)。 –

+0

おそらく、正規表現を使う方が簡単ですが、配列で実際にやりたいのであれば、文字列中の各文字をループし、それらがすべて配列内にあるかどうかを確認する必要があります。あなたがES6を使っているなら、 'username.every(c => allowed.indexOf(c)> -1)'のようなものです。 –

+0

許可された文字列を含む文字列を使用できます。 –

答えて

3

これはまさにregular expressionsが解決するように設計された問題の種類です。この行を交換してみてください:

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

...これで:

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

あなたの要件は、あなたが代わりにあなたの正規表現のためにこれを使用させます同様\w metacharacter、と非常によく似ています

/^[\w-]+$/ 
+0

'/^[\ w - ] + $ /' Perfect。 – Marluxiaz

2

いかがです賭ける:

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

何ワット\がないため、ここを参照してください:MDN Regular Expression

+0

OPの "allowed"リストに含まれていた '-'文字に遭遇すると失敗します。 – jmar777

+0

@ jmar777良い点。編集されました。 – avejidah

0

チェックこのアウト:

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 = " ✔"; 
} 
+0

これは私のために働いています、私のコードに追加していただきありがとうございます。 私は変更されました:if(/^[a-z0-9\-\_]+$/.test(username)){'〜' if(/^[a-z0-9A-Z \ - \ _ \ ] + $ /。test(username)){' – Marluxiaz

関連する問題