简体   繁体   中英

HTML5 input validation through javascript and css not working

I'm trying to create a simple html5 form validation, currently it works on chrome but with a bug, the validation message for the email input does not appear when user inputs an invalid value. It also doesn't work on IE and Firefox.

Here is my current code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Validation message</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<style>

    h1
    {
        margin:0px;
        margin-bottom:6px;
        font-size:1.4em;
    }

    /*fielset
    {
        width:500px;
    }*/

    label
    {
        display:block;
    }

    .none
    {
        display:none;
    }

    .rules
    {
        display:inline;
    }

    input
    {
        border:1px solid #999;
    }

    input:valid
    {
        background:#fff;
    }

    input:invalid
    {
        background:#fcc;
        color:#333;
    }

    .vmsg
    {
        border:1px solid #ccc;
        background-color: #eee;
        padding:4px;
        font-size:0.8em;
        border-radius:5px;
    }


</style>

</head>

<body>
    <form>
        <fieldset>
            <h1>Change Email Adress</h1>
            <label>Username:</label>
            <input type="text" id="username" pattern="[a-zA-Z ]{5,}" placeholder="Username" maxlength="30" required />
            <div id="usernameRules" class="rules">
                <span class="valueMissing vmsg none">The username is required.</span>
                <span class="patternMismatch vmsg none">The username must be a series of alphabetical characters.</span>
            </div>
            <label>Email:</label>
            <input type="email" id="email" name="email" placeholder="Email" required />
            <div class="emailRules" class="rules">
                <span class="valueMissing vmsg none">An email address is required</span>
                <span class="typeMismatch vmsg none">Special characters are not allowed</span>
            </div>

            <div>
                <button type="submit" id="submit" name="submit">Change</button>
                <input type="button" id="checkValidation" name="checkValidation" value="Validate" />
            </div>


        </fieldset>
    </form>

    <script>
        var ruleNames = new Array();
        $(function(){

            //Fills array with rule names.
            //Looks for all elements with 'vmsg' class and then adds
            //the first class (rule name) to the array.
            $(".vmsg").each(function(index, element) {
                if(element.className.indexOf(" ") != -1){
                    ruleNames[index] = element.className.split(" ")[0]; 
                    console.log(ruleNames[index]);
                }
            });

            //Attaches validation event handlers to all input 
            //elements that are Not buttons.
            $(":input:not(:button)").each(function(index, element) {
                this.oninvalid = validationFail;
                this.onblur = validate;
            });

            /*$("#checkValidation").click(function(){
                validate;
            });*/
            document.getElementById("checkValidation").onclick = validate;

        });

        function validate(){
            $(".vmsg").addClass("none");
            document.forms[0].checkValidity();
            //$("form").checkValidity();    
        }

        //Check each input element to determine which
        //element is invalid. Once an invalid state is
        //detected, then loop through the validation rules
        //to find out which is brokern and therefore which
        //message to display to the user
        function validationFail(e){

            /*
                    var elem, evt = e ? e:event;
                if (evt.srcElement){  
                    elem = evt.srcElement;
                }
                else if (evt.target){
                    elem = evt.target
                }
            */

            var element = e.srcElement;

            var validity = element.validity;
            var id = element.id;

            if(!validity.valid){
                for(var i = 0; i < ruleNames.length; i++){
                    checkRule(validity,ruleNames[i], id)
                }
                e.preventDefault();
            }
        }

        //Uses the instance of the input element's
        //ValidityState object to run a validation rule.
        //If the validation rule returns 'true' then the
        //rule is broken and the appropriate validation
        //message is exposed to the user.
        function checkRule(validity,ruleName, id){
            if(eval("validity." + ruleName)){
                //pattern: '#emailRules .valueMissing'
                $("#" + id + "Rules ." + ruleName).removeClass("none");
            }
        }

    </script>

</body>
</html>

Sir/Ma'am, your answers would be of great help. Thank you++

I couldn't reproduce the node itself not working http://jsfiddle.net/HKAHZ/
So maybe your problem is elsewhere.

Why not use some CSS like this

:invalid + .rules > .typeMismatch {display: block;}

The required flag is taking care of error messages if they're ignored, then you just double check server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM