Simple email field in Javascript

Asked

Viewed 48 times

-2

Good afternoon, everyone,

I created an input field to receive email and my only requirement is to ensure that you have a "@" and at least a ".". I read several REGEX to do this validation, but all are too complex and I have very short email addresses on the internal server here in the company, so most of the REGEX ready do not serve me.

Follow my form

<b>E-mail: </b><input name="email" type="text" id="email" value="" size="30" Onkeyup="valida()" required />

Follow my javascript so far:

function valida(){
    var email = document.getElementById("email").value;
    email = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/.toLowerCase();
    document.getElementById("email").value = email;

}

Grateful for the collaboration

  • Because it just doesn’t type="email" in that input??

  • @hugocsl, legacy server with HTML 4

2 answers

2

You can create a regex and use the method search searching in the string o regex valet. in the example I search in the string o @ and a . if there is @in the string it returns the position it is in. if it contracts it returns -1. Basically I see if the search for @ and for . is different from -1, if the email is valid.

let email = document.querySelector('input[type=email]');

function validation() {
if(!email.value) { return console.log('digite algum valor!'); }
  rgx(email.value);
    
}

function rgx(value) {
    if(value.search(/@/) != -1 && value.search(/./) != -1) {
        return console.log('email valido')
    } else {
        return console.log('email invalido')
    }
}
<input type="email">
<button onclick="validation()">valida</button>

1


I made this modification of the above answer, which fully attended me:

function valida(){
var email = document.getElementById("email").value;
email = email.toLowerCase();

if(email.search(/@/) != -1 && email.search(/./) != -1){
    document.getElementById("email").value = email;
    }
else{
    alert('Digite um e-mail válido');
}

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.