Home > front end >  How do you write a field that can allow both username and email address in an html form
How do you write a field that can allow both username and email address in an html form

Time:10-06

I would like to insert a field that can accept both the username and email address in the html form!

<label>Username or e-mail address: </label>
<input type="text">

Also I believe there a need for Javascript used for validation.

CodePudding user response:

Give your input an id:

<input type="text" id="inputID" />

You can use JQuery to check if inputID is an email:

var inputId = $('#inputID').val();

if (inputId.indexOf('@') > -1)
{
  alert("this is an email");
} else {
  alert("this is not an email");
}

You can set the variable using JavaScript if you don't like JQuery. You just have to use getelementbyId.

Hope this helps.

CodePudding user response:

You could get the element by id:

<input type="text" id="input" />


const regEx = new RegExp('^(([^<>()[\]\\.,;:\s@"] (\.[^<>()[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$')

const inputElement = document.getElementById('input');
if(inputElement && inputElement.value){
  if(inputElement.value.match(regEx)
    console.log('Is Email')
  else
    console.log('Is Username')
}

The Regex checks if the input is an email or username.

I hope this helps :)

  • Related