yahoo5000 yahoo5000 - 6 months ago 32
Javascript Question

jquery username validation not working

Hello i am trying to code user validation script for my website but i something is not right cuz its not working properly

:my code
jscript :

$(document).ready(function() {
$('input[name*="username"]').keyup(validateuser);
});

function validateuser() {
var username = $('input[name="username"]').val();

if(username == ""){
$('input[name="username"]').attr('id', 'invalid');
} else {
$('input[name="username"]').validate({
submitHandler: function(form) {
$('input[name="username"]').attr('id', 'valid');
}
});
}
}


and a html input form :

<input type="text" name="username" pattern="[A-Za-z0-9\w]{4,20}"><br>


so all this script have to do is to set a id to input if its valid or if its not and change border color to red or green , so at first if i clear the field and its empty i got red border but if i write something its still stays red and no changes at all , so probably the the second part of code are not working just not sure why , if someone could help me to solve this would be really nice

Answer

Here's a complete example using only jQuery(no plugins):

<head runat="server">
    <title></title>
    <style type="text/css">
        .valid {
            border: 5px solid green;
        }

        .invalid {
            border: 5px solid red;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {

            jQuery('#username').on('input', function () {

                $("#username").removeClass();

                var username = $(this).val();
                var isValid = /^[a-zA-Z0-9]*$/.test(username);
                if (isValid)
                    $("#username").addClass("valid");
                else
                    $("#username").addClass("invalid");
            });
        });
    </script>
</head>
<body>
    <input type="text" name="username" id="username" />
</body>

EDIT:

To validate based on regular expression and character length:

$(function () {

    jQuery('#username').on('input', function () {

        $("#username").removeClass();

        var username = $(this).val();
        var isValid = /^[a-zA-Z0-9]*$/.test(username);
        var length = username.length;
        if (isValid && (length > 4) && (length < 20))
            $("#username").addClass("valid");
        else
            $("#username").addClass("invalid");
    });
});
Comments