Javascript form validation highlight invalid character

1.1k Views Asked by At

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.

I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.

HTML

<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>

<form method="post" action="test.php" onsubmit="return validate()">
    <p><input type="text" id="userName" placeholder="Username or Email"></p>
    <p><input type="password" id="userEmail" placeholder="Password"></p>
    <p><input type="submit" id="submit" value="Login"></p>
</form>

<input type="button" value="debug" onclick="debug()">

<p id="errorText"></p>
<p id="debug"></p>
</body>

Javascript

<script>

    function validate() {
    var userName = document.getElementById('userName').value;
    var userEmail = document.getElementById('userEmail').value;
    var invalidChars = "!,@,#,$,%,^,&,*,(,),<,>,/,~,`";
    var mergeFields = userName.concat(userEmail);
    var found = "false";
    var invCharsArr = invalidChars.split(",");
    var fieldsArr = mergeFields.split("");
    var nameErr = "false";
    var emailErr = "false";

    for (var i = 0; i < fieldsArr.length; i++) {
            if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
            found = "true";
            break;
            }
    }

    if (found == "true") {
        document.getElementById('errorText').innerHTML = "You used an invalid character";
        return false;
    }
    else {
        if (userName == "" || userName == null) {
            document.getElementById('userName').style.backgroundColor = "red";
            document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
            nameErr = "true";
            return false;
        }
        else if (userEmail == "" || userEmail == null) {
            document.getElementById('userEmail').style.backgroundColor = "red";
            document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
            emailErr = "true";
            return false;
        }
        else {
            return true;
        }
    }

    }

</script>

On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks

1

There are 1 best solutions below

0
On

You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.

<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.

As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.