Skip to content Skip to sidebar Skip to footer

Java Script Regular Expression For Detecting Non-ascii Characters

How can we use java script to restrict the use of non-ascii characters in a specific text field..? thanks in advance...

Solution 1:

Ascii is defined as the characters in the range of 000-177 (octal), therefore

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

console.log ( containsAllAscii('Hello123-1`11'));
console.log ( containsAllAscii('ábcdé'));

You probably don't want to accept non-printing characters \000-\037, maybe your regex should be /\040-\176/

Solution 2:

I came accross this page trying to look for a function to sanitize a string to be used as friendly URL in a CMS system. The CMS is multilingual but I wanted to prevent non-ascii characters to appear in the URL. So instead of using ranges, I simply used (based on the solution above):

functionverify_url(txt){
    var str=txt.replace(/^\s*|\s*$/g,""); // remove spacesif (str == '') {
        alert("Please enter a URL for this page.");
        document.Form1.url.focus();
        returnfalse;
    }
    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 falseif(!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;
}

Post a Comment for "Java Script Regular Expression For Detecting Non-ascii Characters"