Reputation: 416
First of all, I checked possible solutions but couldn't find something that helps to solve my problem.
In short, I have existing logic that gets email from user and tests for few conditions, like make sure it doesn't have apostrophe, double @ sign and consecutive dots and etc. The logic is not implemented using regex.
Now, I have new requirement, we need to restrict user from entering non English characters, by restrict I mean try to catch it while user is entering non english character or catch it while value is passed to javascript function that is verifying other conditions above.
So I found some answers here and tried them: here
Here is my code:
<input type="text" id="ctEmailAddress" name="ctEmailAddress" autocomplete="off"
size="40" maxlength="255" value="${userinfo.emailAddress}" oncopy="return false;" onpaste="return false;" onkeypress="suppressNonEng(event)">
And script:
function suppressNonEng(event){
var englishAlphabetAndWhiteSpace = /[A-Za-z ]/g;
var key = String.fromCharCode(event.which);
if (englishAlphabetAndWhiteSpace.test(key)) {
return true;
}
alert ("this is not in English");
return false;
}
So I used js function from link, it is separate from current logic. The problem is, it still allows to pass non english characters, for example french.
The same applies to this function:
function suppressNonEng(event){
var key = event.which;
if(key > 128){
alert("Email address can be entered only in English. Please try again.");
}
}
Again, French letters have no problem going through it.
My question is, how I can make sure that value is english characters only? Should I use regex for that or there is better solution? Please advice. Thanks.
Upvotes: 1
Views: 281
Reputation: 15000
[^\x00-\x7F]+
This regular expression will match any character that is outside ascii 0-127
Live Demo
https://regex101.com/r/qN7eP6/1
Sample text
Here are some sample non-english characters: ü, ö, ß, and ñ.
Sample Matches
[0][0] = ü
[1][0] = ö
[2][0] = ß
[3][0] = ñ
NODE EXPLANATION
----------------------------------------------------------------------
[^\x00-\x7F]+ any character except: ascii 0-127 also known as
'\x00' to '\x7F' (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
Upvotes: 2