简体   繁体   中英

Mask original e-mail on registration page using Javascript

I need to setup a page that allows users to register using their e-mail but as a requirement the e-mail shouldn't be "visible" for human eyes, I guess there's got to be a better way to do it, but so far I came up with this option using JQuery:

I created a fake control that handles the masking and captures the text so that it can be assigned to a hidden field (so that the previously working code will keep working without changes).

var emailControl = $("#eMail");
var firstHalf = "";
var secondHalf = "";
var fullMail = "";

emailControl.keyup(function(e){
  var control = e.currentTarget;
  var currentText = $(control).val();

  if (currentText.length == 0){
    fullMail = '';
    firstHalf = '';
    secondHalf = '';
    $(control).attr('type', 'password');
  }
  else{
    var components = currentText.split("@");
    var hiddenPart = "•".repeat(components[0].length);

    detectChanges(currentText);

    if (components.length == 2) {
      secondHalf = '@' + components[1];
    }

    $(control).attr('type', 'text');
    $(control).val(hiddenPart + secondHalf);
    fullMail = firstHalf + secondHalf;
  }
});

function detectChanges(originalText) {
  var position = originalText.indexOf('@');
  if (position == -1) {
    position = originalText.length;
  }

  for (var i = 0; i < position; i++){
    if (originalText[i] != "•"){
      firstHalf = firstHalf.substring(0, i) + originalText[i] + firstHalf.substring(i+1);
    }
  }
}

I did manage to get it working here: https://codepen.io/icampana/pen/KbegKE

You could give the input tag type of password: type="password". It may cause some janky things to happen with autofill.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <form>
     email: <input type="password" name="email">
  </form>
</body>
</html>

You could also do something similar with CSS

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    input {
      -webkit-text-security: circle;
    }
  </style>
</head>
<body>
  <form>
    email: <input name="email">
  </form>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM