Reputation: 3
i am using the jquery to restrict the language by using the below code and i am unable to show warning message on when we enter other than English language.can anybody help on this issue...
<apex:page controller="testcontroller">
<head>
<apex:includeScript value="{!URLFOR($Resource.Jquery)}" />
<script type="text/javascript">
$(document).ready(function() {
$('#Demo').bind('keyup blur', function() {
$(this).val($(this).val().replace(/[^A-Za-z $]/g, ''))
var regex = new RegExp("[^a-zA-Z]+$");
if(!$(this).value().match(regex)){
alert('Invalid Character usage. Please Use English characters only.');
return false;
}
});
});
</script>
</head>
<apex:form lang="en">
<input Type="Text" id="Demo"/>
</apex:form>
Upvotes: 0
Views: 2559
Reputation: 20344
I think your logic is not quite right. This line
$(this).val($(this).val().replace(/[^A-Za-z $]/g, ''))
Will replace all non-latin characters with '' (i.e. no character). But you do this before you test for that condition and try to alert the user.
Then this line
var regex = new RegExp("[^a-zA-Z]+$");
is supposed to match non-latin characters in the whole word I think, but will only match if there is a non-latin character directly before the end of word (denoted by the $ symbol). It will never match, though, because you've already removed all the non-latin characters.
I think you would be better to try the following, I'm assuming your intention is to alert on the string and then remove the invalid characters:
$(document).ready(function() {
$('#Demo').bind('keyup blur', function() {
if($(this).val().match(/[^A-Za-z ]/g)){
// Pop alert
alert('Invalid Character usage. Please Use English characters only.');
//Replace all the invalid characters with empty string
$(this).val($(this).val().replace(/[^A-Za-z ]/g, ''))
return false;
}
});
});
Example on JS Fiddle: http://jsfiddle.net/ozeu91yg/6/ You might want to play around with other characters, too - for instance I've kept your original form of the RegEx which allows spaces. Do you want to also allow hyphens? All whitespace? and so on. Play around - anything within the [] brackets will be allowed.
EDIT
Just discovered this is a duplicate question, too - see JavaScript Regex (string should include only alpha, space, hyphen) for instance...
Upvotes: 0
Reputation: 304
You have a mistake in a following line:
if(!$(this).value().match(regex)){
use .val()
instead of .value()
Upvotes: 1