jQuery电子邮件验证脚本禁用按钮

时间:2015-02-03 03:48:29

标签: javascript jquery html css validation

这是我的剧本。但它似乎并没有起作用。它没有禁用按钮或阻止表单提交。

<script>
$("#fes-email").on("change", function() {

    if ($("#fes-email").length > 0) {

        $("#fes-email").attr("disabled", "disabled");

    } else {

        $("#fes-email").keyup(function(){

            var email = $("#fes-email").val();

            if(email != 0)
            {
                if(isValidEmailAddress(email))
                {
                    $("#fes-submit").attr("enabled", "enabled");

                } else {
                    $("#fes-submit").attr("disabled", "disabled");  
                }
            }
        });
    }
});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}
</script>

我的HTML:

<input type='email' id="fes-email" name='fes-email' class='fes-input animate' value='' placeholder='E-mail'>
        <input type='submit' id='fes-submit' class='fes-submit animate' value='>'>

不确定是什么问题?

2 个答案:

答案 0 :(得分:2)

您可以尝试类似

的内容
$("#fes-email").on("change keyup", function () {
    var email = $(this).val();
    $("#fes-submit").prop("disabled", email.length == 0 || !isValidEmailAddress(email));
});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

演示

jQuery(function($) {
  $("#fes-email").on("change keyup", function() {
    var email = $(this).val();
    $("#fes-submit").prop("disabled", email.length == 0 || !isValidEmailAddress(email));
  });

  function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='email' id="fes-email" name='fes-email' class='fes-input animate' value='' placeholder='E-mail' />
<input type='submit' id='fes-submit' class='fes-submit animate' value='>' />

答案 1 :(得分:0)

更改if ($("#txtEvent").length > 0)

if ($("#txtEvent").val().length > 0) 

并查看按钮是否已禁用