2011-03-03 4 views
5

Java 스크립트를 사용하여 특정 텍스트 필드에서 비 ASCII 문자 사용을 제한하는 방법은 무엇입니까? 사전에 감사합니다 ...비 ASCII 문자를 검색하는 Java Script 정규 표현식

+0

제거하거나 바꾸시겠습니까? – drudge

+2

Dup : http://stackoverflow.com/questions/3465874/javascript-regex-to-reject-non-ascii-us-characters –

+0

@jnpcl 사용자에게 경고 만합니다. ..... 그들을 제거하는 것도 좋은 옵션입니다. – sasidhar

답변

16

아스키 따라서

function containsAllAscii(str) { 
    return /^[\000-\177]*$/.test(str) ; 
} 

http://jsfiddle.net/V5e4B/1/

당신은 아마 비 동의하고 싶지 않아, 000-177 (진수)의 범위에서 문자로 정의된다 문자를 인쇄 \000-\037, 어쩌면 당신의 정규식은 /\040-\0176/

+2

만약 당신이 원하는 것이 모두 부울이라면,'.exec()'대신'.test()'를 사용해야합니다 - 부울로 변환해야하는 match 객체를 생성하는 대신 부울을 직접 생성합니다. –

+0

감사합니다. Ben, 나는 올바른 방법을 찾기에는 너무 게을 렀다. 제안에 따라 수정 됨 –

1

이 페이지에서 CMS 시스템에서 친숙한 URL로 사용할 문자열을 살균하는 기능을 찾으려고했습니다. CMS는 다국어로되어 있지만 URL에 비 ASCII 문자가 나타나지 않도록하고 싶습니다. 따라서 범위를 사용하는 대신 위의 솔루션을 기반으로 간단히 사용했습니다.

function verify_url(txt){ 
    var str=txt.replace(/^\s*|\s*$/g,""); // remove spaces 
    if (str == '') { 
     alert("Please enter a URL for this page."); 
     document.Form1.url.focus(); 
     return false; 
    } 
    found=/^[a-zA-Z0-9._\-]*$/.test(str); // we check for specific characters. If any character does not match these allowed characters, the expression evaluates to false 
    if(!found) { 
     alert("The can only contain letters a thru z, A thru Z, 0 to 9, the dot, the dash and the underscore. No spaces, German specific characters or Chinese characters are allowed. Please remove all punctuation (except for the dot, if you use it), and convert all non complying characters. In German, you may convert umlaut 'o' to 'oe', or in Chinese, you may use the 'pinyin' version of the Chinese characters."); 
     document.Form1.url.focus(); 
    } 
    return found; 
}