JS写一个所有input项都验证合法后才能点击提交按钮,否则点击提交按钮弹出(‘填写有误’)

2025年03月18日 23:43
有1个网友回答
网友(1):

$("#user").focus(function(){
    $('#p01').empty();
})
$("#psd").focus(function(){
    $('#p02').empty();
});
$("#tel").focus(function(){
    $('#p03').empty();
});

function checkUser() {
    var reguser = /^[a-zA-Z0-9_-]{4,16}$/;
    var user = $('#user');
    if( $("#user").val().length == 0 ){
        $("#p01").html("账户不能为空");
        $("#p01").css("color","red");
        return false;
    }else if(reguser.test(user.val())){
        $("#p01").html("用户名输入正确");
        $("#p01").css("color","blue");
        return true;
    }else{
        $("#p01").html("用户名为4-16位字母,数字,下划线,减号");
        $("#p01").css("color","red");
        return false;
    }
}

function checkTel() {
    var regtel = /^1[3|4|5|7|8][0-9]{9}$/;
    var tel = $('#tel');
    if( $("#tel").val().length == 0 ){
        $("#p03").html("号码不能为空");
        $("#p03").css("color","red");
        return false;
    }else if(regtel.test(tel.val())){
        $("#p03").html("手机号输入正确");
        $("#p03").css("color","blue");
        return true;
    }else{
        $("#p03").html("请输入正确的手机号");
        $("#p03").css("color","red");
        return false;
    }

}

function checkPassword() {
    var regpsda =/[0-9|a-z|A-Z]/;
    var regpsdb =/^[a-zA-Z]+$/; //该出密码强度设计不够严谨
    var regpsdc =/[^0-9a-zA-Z]/;
    var psd = $('#psd');
    if( $("#psd").val().length == 0 ){
        $("#p02").html("密码不能为空");
        $("#p02").css("color","red");
        return false;
    }else if(regpsda.test(psd.val())){
        $("#p02").html("密码强度低");
        $("#p02").css("color","indianred");
        return true;
    }else if(regpsdb.test(psd.val())){
        $("#p02").html("密码强度中");
        $("#p02").css("color","chocolate");
        return true;
    }else if(regpsdc.test(psd.val())){
        $("#p02").html("密码强度高");
        $("#p02").css("color","green");
        return true;
    }else{
        $("#p02").html("密码位6-12位字母数字组合");
        $("#p02").css("color","red");
        return false;
    }

}

$('#btn').on('click',function () {
    var user=checkUser();
    var tel=checkTel();
    var psd=checkPassword();
    if(user && tel && psd){
        alert('提交');
    }else {
        alert('填写有误');
    }
});

改写好了 你自己直接替换进去 判断逻辑沿用你自己的,只是密码强度这块需要你自己衡量,例如密码强度弱不给提交 那对应的

else if(regpsda.test(psd.val())){
        $("#p02").html("密码强度低");
        $("#p02").css("color","indianred");
        return true;
    }

这个return改为false。表单的提交话在把alert('提交')改为 $('#form').submit();