Count the number of characters changed in an input field

3

On a given page to change the registered data, in one of the fields I need to limit the amount of characters that can be changed. There are 2 inputs fields and one of them is hidden by storing the name in the current form. In% visible% is also stored the name in the current format and the user can make changes. I used input when the user exits the field a script js compares the hidden input string with the visible input, if there are more than 3 changes a message is passed to the user and the name returns to the previous format.

The problem is that I did not get a logic that meets all the rules, what complicates the case is that characters can be removed, changed or inserted , ie if the Hnrikuei is saved and the user wants to correct for Henry three changes must be counted. One for the e added, one for the i removed and another for the k changed for q. I'm a beginner in JavaScript and would like to know if you do not have any tools that would help you create something to meet this rule.

    
asked by anonymous 15.11.2015 / 17:20

2 answers

4

The Distance from Levenshtein is one of the best-known algorithms for calculating the difference between two strings .

See an adaptation of another question for your specific case:

function levenshtein(str1, str2) {
  var m = str1.length,
      n = str2.length,
      d = [],
      i, j;

  if (!m) return n;
  if (!n) return m;

  for (i = 0; i <= m; i++) d[i] = [i];
  for (j = 0; j <= n; j++) d[0][j] = j;

  for (j = 1; j <= n; j++) {
    for (i = 1; i <= m; i++) {
      if (str1[i-1] == str2[j-1]) d[i][j] = d[i-1][j-1];
      else d[i][j] = Math.min(d[i-1][j], d[i][j-1], d[i-1][j-1])+1;
    }
  }
  return d[m][n];
}

// Daqui para baixo, o código é apenas para demonstração de uso.
function calc() {
  var t1 = document.getElementById('t1');
  var t2 = document.getElementById('t2');
  var r1 = document.getElementById('r1');
  var d  = levenshtein( t1.value, t2.value );
  r1.innerHTML = d;
  r2.innerHTML = d>3?'Não':'Sim';
}
calc();
<strong>Altere os campos para testar a função</strong><br>
Palavra 1:<br>
<input id="t1" type="text" value="Hnrikuei" onKeyUp="calc()"><br>
Palavra 2:<br>
<input id="t2" type="text" value="Henrique" onKeyUp="calc()"><br>
Diferença:<br>
<div id="r1">?</div>
Valida (até 3):<br>
<div id="r2">?</div>


Follow a link recommended by @Cold with similarity measurement techniques between strings:
link

a>

    
15.11.2015 / 18:54
1

Well, I made an example in JsFiddle: link

You will notice that there are two text boxes. Basically, the system will check for a difference of more than 3 characters.

    function verifyChange(){

        var span = document.getElementsByTagName("span")[0];

        var name = document.getElementById("name_user");
        var correcao = document.getElementById("correcao_name_user");

        var char1 = []; //quantidade de caracteres do name_user
        var char2 = []; //quantidade de caracteres do correcao_name_user

        for(var i = 0; i < name.value.length; i++){
            char1[i] = name.value.substring(i, i+1);
        }
        for(var j = 0; j < correcao.value.length; j++){
            char2[j] = correcao.value.substring(j, j+1);
        }
        if(char1.length - char2.length > 3 || char2.length - char1.length > 3){

            span.innerHTML = "Modificação inválida.";

        }else{
            var NCrt = 0; //nº de caracteres modificados
            var n = 0;
            if(char1.length == char2.length){
                for(var i = 0; i < char1.length; i++){
                    if(char1[i] != char2[i]){
                        NCrt++;
                    }
                }
            }else{
                if ( char1.length < char2.length){
                    Mlength = char1.length
                    
                    for(var j = 0; i < char2.length; i++){
                        for(var i = 0; i < char1.length; i++){
                            if(char1[j] != char2[i]){
                                NCrt++;
                            }
                    	}
                        if(NCrt == char2.length){
                        	n++;
                        }
                    }
                }else {
                    
                    for(var j = 0; i < char1.length; i++){
                        for(var i = 0; i < char2.length; i++){
                            if(char2[j] != char1[i]){
                                NCrt++;
                            }
                    	}
                        if(NCrt == char1.length){
                        	n++;
                        }
                    }
                }
            }
            if(NCrt > 3 || n > 3){
                span.innerHTML = "Modificação inválida.";
            }else{
            	span.innerHTML = "Modificação válida.";
            }
        }
    }
<form action="javascript: verifyChange()">
  <input type="text" onblur="verifyChange()" id="name_user" value="George">
  <input type="text"  onblur="verifyChange()"  id="correcao_name_user" value="gege">

  <input type="submit" value="Verificar" onclick="verifyChange()">
  <br>
  <br>
  <span></span>

</form>

I made it in pure javascript anyway.

The property substring , works by capturing the character of String , for example:

    var ex = "Exemplo";
    ex.substring(0, 3);

It would result in:

    Exe

It counts as if it works just like a selection:  | E | x | e | m | p | l | o |

In the above case, he selected from the first bar (0) to the fourth (3).

See more about subtring here: link

There is also substr , explained here: link

    
15.11.2015 / 18:13