检查电子邮件验证并在“电子邮件阻止”字段下输入错误

时间:2018-10-10 03:13:05

标签: javascript html validation email

检查电子邮件验证并在“电子邮件阻止”字段下输入错误

function email_check()
{
    var email = document.getElementById('email').value;
    var datas = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    if(datas.test(email) == false)
    {
        document.getElementById('errorpassword').innerHTML = "this is an invalid email";   
    }

    return false;
}


<input type ="email" placeholder="email id" id="email" required onblur="email_check(this.value)"/>
<span id="erroremail"></span>

2 个答案:

答案 0 :(得分:0)

尝试以下代码,并根据需要对其进行编辑

function validateEmail(email) {
  var re = /^(([^<>()[\]\\.,;:\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,}))$/;
  return re.test(email);
}

function validate() {
  var $result = $("#result");
  var email = $("#email").val();
  $result.text("");

  if (validateEmail(email)) {
    $result.text(email + " is valid :)");
    $result.css("color", "green");
  } else {
    $result.text(email + " is not valid :(");
    $result.css("color", "red");
  }
  return false;
}

$("#validate").bind("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p>Enter an email address:</p>
  <input id='email'>
  <button type='submit' id='validate'>Validate!</button>
</form>

<h2 id='result'></h2>

答案 1 :(得分:0)

HTML代码:

     <div class="form-group">
                <label class="control-label" for="event-mail">Email: </label>
<div class="events">
                    <input id="emailaddress" name="emailaddress" placeholder="Email Address" type="email" data-error-empty="Please enter your email" data-error-invalid="Invalid email address" >
</div>
                <button name="submit" id="validate" type="submit"> Validate
        </button>

            </div><!-- End Email input -->

JS代码:

$(document).ready(function () {
    $('#validate').click(function () {
    $('.error-message').remove();
    $('.success-message').remove();
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
alert($('#emailaddress').val());
                if (!emailReg.test($.trim($('#emailaddress').val()))) {
                    var invalidEmail = $('#emailaddress').data('error-invalid');
                    $('#emailaddress').parents('.events').append('<span class="error-message" style="display:none;">' + invalidEmail + '.</span>').find('.error-message').fadeIn('fast');
                    $('#emailaddress').addClass('inputError');
                }
                else
                {
                $('#emailaddress').parents('.events').append('<span class="success-message" style="display:none;">Valid email address.</span>').find('.success-message').fadeIn('fast');
                $('#emailaddress').addClass('inputSuccess');
                }
});
});

CSS:

.inputError{
 color: red;
}
.inputSuccess{
 color: green;
}

Jsfiddle