2

I need help for my register form. I'm registering users with their website link, email and password. I need some jQuery script to disallow users to change the prefix of their email. So for example they putted https://google.com for their website => which automatically allow only @google.com email to be written down below in the email input. One more example:

Website: https://youtube.com

Allowed Email: john@youtube.com

Disallowed Email: john@outlook.com

I tried with:

<script>
$("#email").on('keyup input change', function() {
    var val = $(this).val();
    if(val.indexOf("@outlook.com") != 1) {
        $(this).val(val + '@outlook.com');
    }
});
</script>

but that's absolutely not what I expect. Besides everything, I need to figure out a way to get only the domain from the link..

Any ideas?

Thanks in advance!

  • Please show us what your have tried, and keep in mind that Stack overflow is not a coding service. – Carsten Løvbo Andersen Nov 16 '21 at 13:40
  • 2
    Also worth noting: This cannot be done completely client side in a "secure" way. The best you can do with JS is validate the input and give UI pointers, you still require server side checks for this to be enforced. – DBS Nov 16 '21 at 13:44

2 Answers2

0

Just wrap your link into URL constructor, which will give you detailed information about the link, and then just use string method includes() to check whether its true or false

let host = new URL("https://youtube.com").hostname;
let input = $("input").val()
if(!input.includes(`@${host}`)) return false
Tiko
  • 1,241
  • 11
  • 19
  • `$("#email").on('keyup input change', function() { var $this = $(this); var val = $(this).val(); var link = $("#link").val(); let host = new URL(link).hostname; if(!$this.includes('@${host}')) return false });` getting error **$this.includes is not a function** –  Nov 16 '21 at 13:56
  • @keneferinho95 I think `$this.includes('@${host}')` should be `val.includes('@${host}')` – Carsten Løvbo Andersen Nov 16 '21 at 13:56
  • @CarstenLøvboAndersen true, now getting an error **Uncaught TypeError: URL constructor: undefined is not a valid URL.** –  Nov 16 '21 at 13:58
  • Check if you're getting the link right – Tiko Nov 16 '21 at 13:59
  • yep, getting it right. Checked it with `alert(link);` –  Nov 16 '21 at 14:03
  • So finally no error showing up, but still not what I need. the final code now is: `$("#email").on('keyup input change', function() { var $this = $(this); var val = $(this).val(); var link = $("#link").val(); let host = new URL(link).hostname; if(!val.includes('@${host}')) { console.log('no'); } else { console.log('yes'); } });` –  Nov 16 '21 at 14:03
  • When I type a correct email I'm not getting console log "yes" as expected. –  Nov 16 '21 at 14:04
  • does your val come right as well? – Tiko Nov 16 '21 at 14:06
  • Yes, also checked it with `alert(val);`. –  Nov 16 '21 at 14:10
  • can u provide jsfiddle? – Tiko Nov 16 '21 at 14:11
  • https://jsfiddle.net/f6thjuob/1/ –  Nov 16 '21 at 14:15
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals Seems cant use string literals in comment section, change ' to ` – Tiko Nov 16 '21 at 14:25
  • Ok, works fine. So now how can i add the prefix needed in the user input (and removing the disallowed if necessary)? –  Nov 16 '21 at 14:36
0

The example below acts as you have requested, I've added in some error checking and usability improvements. Hopefully this is roughly what you needed and can tweak this for your specific case.

It converts any domain provided into a hostname as per the answer here. Effectively using a trick using an a tag.

User changes into the email input automatically have the correct domain added as a suffix, values are gathered or set using .val() and strings manipulated using .substr() or .replace(). The user's position is not lost so they can continue to type as they enter their username using .setSelectionRange().

Error checking is performed on the email input, although this is less necessary as we are leading the user to the correct input by automatically adding the correct hostname suffix. It will reject input that does not end with the correct hostname, or that has multiple "@" by using .split("@").length (as we know the resultant array of a correctly formatted email should only have two elements).

A message is shown informing the user if there is an error (via CSS styling and .show()), this persists once shown as otherwise it would be automatically hidden with the automatic correction. The specific hostname required is provided in the message, and updated with changes to the user inputed domain.

The code is fully commented so should be self-explainatory.


DEMONSTRATION

// Setup variables to help simplify code later
var username = "";
var domain = "";
var emailDomain = "";

// Load initial values (not needed in reality unless you want to suggest a domain to users)
domain = url_domain($("#domain").val());
emailDomain = "@" + domain;
$("#hostname").text(emailDomain);


// Key track of current domain
$("#domain").on('keyup input change', function() {
  
  // Update variables
  domain = url_domain($(this).val());
  emailDomain = "@" + domain;
  
  // Update error message
  $("#hostname").text(emailDomain);
  
});



// Check user input on email 
$("#email").on('keyup input change', function() {

  // Get username (by removing auto added domain if present)
  username = $(this).val().replace(emailDomain, "");
  
  // Add domain back / initially
  $(this).val(username + emailDomain);
  
  // Set selection to appropriate place on username
  // Improves user experience
  document.getElementById('email').setSelectionRange(username.length, username.length);


  // Prepare for error checking
  val = $(this).val();
  
  // Ensure the correct domain is at the end of the address, and that two domains are not provided.
  if (val.substring(val.length - emailDomain.length) != emailDomain || val.split("@").length > 2) {

    // Show warning if error present
    $("#email-warning").show();
    
    // Remove extra /incorrect domain
    $(this).val(val.substr(0, val.indexOf("@")));

  }    

});


// Gets hostname from domain passed to it
// Original answer - https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string
function url_domain(data) {
  var a = document.createElement('a');
  a.href = data;
  return a.hostname;
}
#email-warning {
  color: red;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="domain" value="http://google.com">
<input id="email" placeholder="E-mail">
<p id="email-warning">You can only register with an email linked to your domain (<span id="hostname"></span>).</p>
Oliver Trampleasure
  • 3,293
  • 1
  • 10
  • 25