如何在ajax中检查密码是否少于8个字符?

时间:2016-05-10 16:16:50

标签: javascript jquery ajax forms

我正在尝试检查用户的密码或用户名是否少于8个字符,我之前已经这样做了,只是在我的表单中使用onsubmit="return Validation()",并且它正在以这种方式工作。但现在我通过ajax发送表单,我不知道如何在我的ajax代码中转换或插入以下代码。

下面是我想要包含在我的ajax代码中的代码,所以当我提交表单时,它会检查用户是否少于8个字符的用户名和密码。

function Validation(){
var username = document.getElementById ("username");            
var password = document.getElementById ("password");

var username = $("#username").val();
var password = $("#password").val();
var password2 = $("#password2").val();

var user_textBox = document.getElementById("username");
var user_textLength = user_textBox.value.length;

var pw_textBox = document.getElementById("password");
var pw_textLength = pw_textBox.value.length;

var x = email;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if(user_textLength <= 7){
    alert('Username must contain atleast 8 characters.');
    document.getElementById ("username").focus();
    return false;
    }
    else if(pw_textLength <= 7){
        alert('Password must contain atleast 8 characters.');
        document.getElementById ("password").focus();
        return false;
        }
    else if(password2==""){
        alert('Please re-type your password');
        document.getElementById ("password2").focus();
        return false;
    }
    else if(password != password2){
        alert('Password and Re-typed Password do not match');
        document.getElementById ("password2").focus();
        return false;
    }
    else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address");
        document.getElementById ("email").focus();
        return false;
    }
    else{
        return true;
    }
}

下面是我的ajax代码。

$('document').ready(function(){
    function submitForm()
    {       
        var data = $("#signUpForm").serialize();
        $.ajax({
            // code here...
        });
        return false;
    }

    $("#signUpForm").on("submit",submitForm);
    document.forms["signUpForm"].reset();
});

编辑: 我的代码现在是什么样的

$('document').ready(function()
{
    $('#signUpForm').submit(function(e)){
        function Validation() {
            var username = document.getElementById ("username");            
            var password = document.getElementById ("password");

            var username = $("#username").val();
            var password = $("#password").val();
            var password2 = $("#password2").val();

            var user_textBox = document.getElementById("username");
            var user_textLength = username.trim().length;

            var pw_textBox = document.getElementById("password");
            var pw_textLength = password.trim().length;

            var x = email;
            var atpos = x.indexOf("@");
            var dotpos = x.lastIndexOf(".");
            if(user_textLength <= 7){
                    alert('Username must contain atleast 8 characters.');
                    document.getElementById ("username").focus();
                    return false;
                }
                else if(pw_textLength <= 7){
                    alert('Password must contain atleast 8 characters.');
                    document.getElementById ("password").focus();
                    return false;
                }
                else if(password2==""){
                    alert('Please re-type your password');
                    document.getElementById ("password2").focus();
                    return false;
                }
                else if(password != password2){
                    alert('Password and Re-typed Password do not match');
                    document.getElementById ("password2").focus();
                    return false;
                }
                else if(email==""){
                    alert('Please input your email');
                    document.getElementById ("email").focus();
                    return false;
                }
                else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
                    alert("Not a valid e-mail address");
                    document.getElementById ("email").focus();
                    return false;
                }

                else{
                    return true;
                }
        }
        if(!Validation()){
            e.preventDefault();
            return false;
        } else {
            //var data = $("#signUpForm").serialize();

                $.ajax({

                type : 'POST',
                url  : 'signup.php',
                data : $(this).serialize()
                beforeSend: function()
                {   
                    $("#error").fadeOut();
                    },
                success :  function(data)
                           {                        
                                if(data==2){

                                    $("#error").fadeIn(1000, function(){


                                            alert('Email is already taken.');
                                            document.getElementById ("email").focus();

                                    });

                                }
                                else if(data==1){
                                    $("#error").fadeIn(1000, function(){


                                            alert('Username is already taken.');
                                            document.getElementById ("username").focus();
                                    });
                                }
                                else if(data==3)
                                {

                                    alert('Registration successfully submitted.');
                                    window.location='index.php';

                                }
                                else{

                                    $("#error").fadeIn(1000, function(){

                        $("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+data+' !</div>');

                                    $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account');

                                    });

                                }
                           }
                });
                return false;
            }
    });
     $("#signUpForm").on("submit",submitForm);
     document.forms["signUpForm"].reset();
}); 

2 个答案:

答案 0 :(得分:0)

完全一样:

    if(user_textLength <= 7){
       return false; // function breaks here, following sentences will not execute
    }
    var data = $("#signUpForm").serialize();
    $.ajax({
         //....

答案 1 :(得分:0)

如果您想忽略前导或尾随空白区域,可以在length调用后查看trim()属性来检查值的长度:

function Validation(){
    // Get your properties
    var username = $("#username").val();
    var password = $("#password").val();
    var password2 = $("#password2").val();

    // Validation example
    if(username.trim().length < 8){
         // Something is wrong, tell the user
         return false;
    }

    // Continue as necessary
} 

由于您已经在使用jQuery,因此您可以通过连接事件处理程序来捕获表单提交事件,如下所示:

$(function(){
     // When your form is submitted
     $('#signUpForm').submit(function(e){
           // Validate here
           if(!Validation()){
                // Validation failed
                e.preventDefault();
                return false;
           } else {
               // Otherwise handle your AJAX request
               $.ajax({
                   // Various things here
                   data: $(this).serialize()
               });
           }
     });
});

<强>更新

由于您最近添加了代码,我将通过删除您的表单提交范围内的Validation()函数来重构它,删除任何默认提交行为(因为它似乎是通过AJAX处理的)并删除任何本机Javascript调用,支持jQuery(因为您已经在使用它):

<script>
     function Validation() {
            // Define your variables
            var username = $("#username").val();
            var password = $("#password").val();
            var password2 = $("#password2").val();
            // Get your lengths
            var user_textLength = username.trim().length;
            var pw_textLength = password.trim().length;

            var x = email;
            var atpos = x.indexOf("@");
            var dotpos = x.lastIndexOf(".");
            if(user_textLength <= 7){
                    alert('Username must contain atleast 8 characters.');
                    $("#username").focus();
                    return false;
            }
            else if(pw_textLength <= 7){
                    alert('Password must contain atleast 8 characters.');
                    $("#password").focus();
                    return false;
            }
            else if(password2.length == 0){
                    alert('Please re-type your password');
                    $("#password2").focus();
                    return false;
            }
            else if(password != password2){
                    alert('Password and Re-typed Password do not match');
                    $("#password2").focus();
                    return false;
            }
            else if(email.length == 0){
                    alert('Please input your email');
                    $("#email").focus();
                    return false;
            }
            else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
                    alert("Not a valid e-mail address");
                    $("#email").focus();
                    return false;
            }
            else {
                return true;
            }
    }
    $(function(){
        $('#signUpForm').submit(function(e)){
            // Prevent the default submission regardless (as it will be handled via AJAX
            e.preventDefault();
            if(!Validation()){
                return false;
            } else {
                $.ajax({
                    type : 'POST',
                    url  : 'signup.php',
                    data : $(this).serialize()
                    beforeSend: function(){   
                        $("#error").fadeOut();
                    },
                    success: function(data){                        
                        if(data==2){
                            $("#error").fadeIn(1000, function(){
                                alert('Email is already taken.');
                                $("#email").focus();
                            });
                        } else if(data==1){
                            $("#error").fadeIn(1000, function(){
                                alert('Username is already taken.');
                                $("#username").focus();
                            });
                        } else if(data==3){
                                alert('Registration successfully submitted.');
                                window.location='index.php';
                        } else{
                                $("#error").fadeIn(1000, function(){
                                    $("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+data+' !</div>');
                                    $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account');
                                });
                        }
                    }
                });
            }
        });
    }); 
</script>