Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery maxlength "æ" or "ø" or "å" should count as two characters

I want to send text through a sms gateway, and they have a limit of 11 characters, in the from field. and æ or ø or å count as two characters. I use jquery validator, to count, and show user message, how do I get maxlength, to minus two every time, the users enter æ or ø or å, and only minus one character, when it's from a-z ??

Right now the script, allow a-z and æøå, 0-9 and space, but it don't count æøå as two characters. how do I do that?

jQuery.validator.addMethod("accept", function(value, element, param) {
return value.match(new RegExp("^" + param + "$"));
});
from: {
            required: false,
            accept: "[a-zA-Z0-9æøåÆØÅ ]+",
            minlength: 2,    
            maxlength: 11
},
like image 407
Anders Avatar asked Feb 10 '14 08:02

Anders


2 Answers

Try something like this:

function countChar(mystring){
    var count=0;
    for (var i=0;i<mystring.length;i++)
    {
        if (mystring[i].match(/[æøåÆØÅ]/))
            count += 2;
        else
            count++;
    }
    return count;
}
like image 125
ojovirtual Avatar answered Oct 04 '22 21:10

ojovirtual


You need to encode it first.

function encode_utf8(s) {
  return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
  return decodeURIComponent(escape(s));
}

You can take a look at http://jsfiddle.net/vLmQ8/ to see it in action.

Please see http://monsur.hossa.in/2012/07/20/utf-8-in-javascript.html for more information.

like image 45
Gagaro Avatar answered Oct 04 '22 23:10

Gagaro