允许(破折号)& (数字)在正则表达式中为非英语字符

时间:2014-12-18 10:53:39

标签: javascript jquery regex

jSFiddle示例仅接受阿拉伯语字符,如果您输入英语字符或偶数数字/短划线,则会发出警报

1-我需要让它接受数字&短跑
2-接受数字或破折号,以防它在输入值和&之间。如果它在开头或结尾就拒绝它。

例如:

  • 阿拉伯语----字符[正确]

  • arabic7777chars [正确]

  • arabicchars ---- [不正确]

  • 77777arabicchars [不正确]

至少我需要它接受数字&破折号,提前致谢

HTML 的

<div class="search-bar">
    <input type="text" class="name">
    <input type="submit" value="submit">

JS 的

$(document).ready(function(e){
    $('.search-bar').on('change', '.name', function(e) {
        var is_arabic = CheckArabicOnly(this);
    });    
});

function CheckArabicOnly(field) {
var sNewVal = "";
var sFieldVal = field.value;
for(var i = 0; i < sFieldVal.length; i++) {
    var ch = sFieldVal.charAt(i);;
    var c = ch.charCodeAt(0);
    var dash = "-";
    if(c < 1536 || c > 1791) {
        alert("Please Enter AR characters");
        field.value = '';
        return false
    }
    else {
        sNewVal += ch;
    }
}
field.value = sNewVal;

return true;
}

jSFiddle

2 个答案:

答案 0 :(得分:1)

这似乎做了你正在寻找的事情

^([\u0600-\u06FF]+)(\d*|-*)([\u0600-\u06FF]+)$

https://regex101.com/r/kG8fF1/1

如果您想匹配&#34; -7-7 - &#34;之类的东西,只允许使用短划线或仅允许数字,用[\d-]*替换中间部分:

^([\u0600-\u06FF]+)([\d-]*)([\u0600-\u06FF]+)$

答案 1 :(得分:1)

另一种解决方案类似于以下内容:

   $(document).ready(function(e){
    $('.search-bar').on('change', '.name', function(e) {
        var is_arabic = CheckArabicOnly(this);
    });    
});
     function CheckArabicOnly(field) {
    var sNewVal = "";
    var sFieldVal = field.value;
    //If the string starts or ends with dashes or digits, this will match and the function will exit. The middle section will check to see if there are more than two consecutive dashes in the string.
         var reg = new RegExp("(^(\d|-))|(-{2,})|((\d|-)$)");
    if(reg.test(sFieldVal))
    {
       alert("Invalid");
       return false;
    }
    for(var i = 0; i < sFieldVal.length; i++) {
        var ch = sFieldVal.charAt(i);
        var c = ch.charCodeAt(0);        
        var dash = "-";  
        //45 is the value obtained when a digit is used, so we add it to the list of exceptions.     
        if((c != 45) && (c < 1536 || c > 1791)) {
            alert("Please Enter AR characters");
            field.value = '';
            return false
        }
        else {
            sNewVal += ch;
        }
    }
    field.value = sNewVal;

    return true;
}