2015-01-28 5 views
0

사용자가 특정 단어 및 특수 문자를 "and", "or", "/", "\"등의 텍스트 필드에 입력하는 것을 방지하려고합니다. 변수를 두 개 이상의 조건으로 설정하는 방법 또는이 변수에 어느 정도 접근해야합니까?자바 스크립트 유효성 검사 특정 단어 금지

사용자가 "and"또는 텍스트 필드에 입력하는 것을 방지하려고 시도하고있었습니다.

function watchForWords(text) { 
    if (!text) { 
    return true; 
    } 
    var isValid = (text.value != "and" || text.value != "or"); 
    if (!isValid) { 
    text.style.backgroundColor = "#ff8"; 
    } 
return isValid; 
} 
+0

입니다. var isValid = (text.value! = "및"&& text.value! = "또는"); ' – Blazemonger

+0

[스위치] (http://www.w3schools.com/js/js_switch.asp) 문을보십시오. – levi

+0

'text.value.match (/ (및 | or | \/| \\) /)' – adeneo

답변

3

"단어"를 정의하는 방법에 따라 몇 가지 옵션이 있습니다. 문자열을 의미하는 경우 indexOf과 같은 간단한 문자열을 사용하여 한 문자열에 다른 문자열이 들어 있는지 확인할 수 있습니다. 말 그대로 단어를 의미하는 경우, 공백으로 구분 된 의미에서 정규식이 필요할 것입니다.

간단한 :

var blacklist = ["and", "or", "/", "\\"]; 
 

 
function validate(input) { 
 
    for (var i = 0; i < blacklist.length; ++i) { 
 
    if (input.indexOf(blacklist[i]) >= -1) { 
 
     // String is present 
 
     return false; 
 
    } 
 
    } 
 
    // No blacklisted strings are present 
 
    return true; 
 
} 
 

 
console.log("this is a clean string", validate("this is a clean string")); // true 
 
console.log("and this is a dirty string", validate("and this is a dirty string")); // false 
 
console.log("andthis is also dirty", validate("andthis is also dirty")); // false

정규식 :

var blacklist = ["and", "or", "/", "\\"]; 
 

 
function validate(input) { 
 
    for (var i = 0; i < blacklist.length; ++i) { 
 
    var expr = new RegExp("\\b" + blacklist[i] + "\\b"); 
 

 
    if (expr.exec(input)) { 
 
     // String is present 
 
     return false; 
 
    } 
 
    } 
 
    // No blacklisted strings are present 
 
    return true; 
 
} 
 

 
console.log("this is a clean string", validate("this is a clean string")); // true 
 
console.log("and this is a dirty string", validate("and this is a dirty string")); // false 
 
console.log("andthis is also dirty", validate("andthis is also dirty")); // true, note the difference from the previous because of no word sep

2
var isValid = !/(\w+)?and|or|\/|\\\w+/.exec(myString) 

isValid는 "and"또는 "or"또는 사용자가 명시한 다른 문자를 포함하지 않으면 true이고