Search code examples
c#asp.net-mvcdata-annotationsmultilingual

Validating text in other language using data annotation in asp.net mvc 4


I am using data annotations in asp.net mvc 4 to validate my username text box as follows:

[Required()]
[RegularExpression("^[a-zA-Z]{4,15}$")]
public string USER_NAME { get; set; }

User can enter any username with minimum length of 4 and maximum length of 15. Also user can enter username in any language. This works fine when I enter English text but when I enter or copy paste text in that field with other language like arabic or other it doesn't validate it so how to do this validation.

Thanks in advance...


Solution

  • This concept appears to work and tested successfully on my end, in the code below there are two text boxes and during the onchange event we call two different functions CheckEnglishOnly and CheckArabicOnly which retrieve the string and check every character in the string. The charCodeAt function is used to get the decimal value of the character and for English it checks that the value is between 0 and 255, for Arabic it checks that the character value is between 1536 and 1791 which according to this website http://www.alanwood.net/unicode/arabic-supplement.html appears to be the range for Arabic characters. Characters that do not qualify are discarded and the text field value is updated at the end.

    You might also find the Unicode chart for Arabic at http://www.unicode.org/charts/PDF/U0600.pdf useful.

    I have tested the code in IE and FF successfully. I hope this useful to you!

     <script type="text/javascript">
    
    function CheckEnglishOnly(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);
    
            if(c < 0 || c > 255) {
                // Discard
            }
            else {
                sNewVal += ch;
            }
        }
    
        field.value = sNewVal;
    }
    
    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);
    
            if(c < 1536 || c > 1791) {
                // Discard
            }
            else {
                sNewVal += ch;
            }
        }
    
        field.value = sNewVal;
    }
    
    </script>
    

    Then in the html body tag:

    English Only (onchange): <input type="text" id="txtEnglish" onchange="CheckEnglishOnly(this);" />
    Arabic Only (onchange): <input type="text" id="txtArabic" onchange="CheckArabicOnly(this);" />