Reputation: 844
I am create small demo for write persian text enter in text box.i am search some links and try this code but this is not enter persian text enter only english text so can you please help me how can do that.and also want to validation on national id.
this is my html text box :
<input type="text" id="txtn" onkeypress="text(this)">
this is my js code :
function text(name)
{
var name = $(name).val();
just_persian(name);
}
function just_persian(str) {
var p = /^[\u0600-\u06FF\s]+$/;
if (!p.test(str)) {
alert("not format");
}
}
here i am enter any text always getting alert.
Upvotes: 6
Views: 5068
Reputation: 117
Try this code:
document.getElementById('nameFa').addEventListener('keypress',function(e){
if ((e.charCode >= 97 && e.charCode <= 122) || (e.charCode>=65 && e.charCode<=90)){
alert("Language is english");
e.preventDefault();
}
else if(isPersian(e.key))
alert("Language is Persian");
else
alert("Others");
});
function isPersian(str){
var p = /^[\u0600-\u06FF\s]+$/;
return p.test(str);
}
And
<input type="text" id="nameFa">
Upvotes: 0
Reputation: 5746
If you would like to keep most of the code as it is, I would suggest checking that the name is not empty before validating and checking on the keyup
event, after the character is available. Otherwise, the validation fails because the regex requires at least one character. Please note @yashar-aliabasi has a good answer because the validation will also run on pasting and the textbox triggering a change event as well as preventing invalid characters from entering the textbox.
function text(name)
{
var name = $(name).val();
if (name.length > 0) {
just_persian(name);
}
}
function just_persian(str) {
var p = /^[\u0600-\u06FF\s]+$/;
if (!p.test(str)) {
alert("not format");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtn" onkeyup="text(this)" value="">
Upvotes: 4
Reputation: 2719
Try this code:
$("#txtn").on('change keyup paste keydown', function(e) {
if(just_persian(e.key) === false)
e.preventDefault();
});
function just_persian(str) {
var p = /^[\u0600-\u06FF\s]+$/;
if (!p.test(str)) {
return false
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtn">
I hope this work :)
Upvotes: 15