Skip to content Skip to sidebar Skip to footer

Javascript To Prevent Invalid User Input

I have written a set of javascript functions that allow me to validate user input on a form. I only want to accept valid input, and impose the following behaviour: When a user ente

Solution 1:

When loading the page, couldn't you create a hidden form value or js variable in which you store the initial/default value for the field? When they change the form field, validate it, and if it passes, update the hidden field or js variable to match that in the field they updated.

When the input given by the user fails validation, show the invalid entry along with the error message and then update the form field back to the value you have saved which would be either the default value or the last valid value that they entered.

EDIT:
Note that this is only a quick and (very) dirty example of doing what I explained in my answer above. If you have a lot of inputs, you will probably want to store the values in an associative array instead of in hidden form values, but this should give you a good handle on what I am suggesting. I would also strongly encourage you to NOT use alert boxes for notification of invalid answers.

<html>
<head>
<script type="text/javascript">
    function validate()
    {
        var field1 = document.getElementById("field1");
        var saved  = document.getElementById("field1_save");
        if (field1.value < 0 || field1.value > 10)
        {
            alert("Field1 value of " + field1.value + " is invalid");

            // Change the value back to the previous valid answer
            field1.value = saved.value;
            return false;
        }

        // Save the valid input
        saved.value = field1.value;
        return true;
    }
</script>
</head>

<body>
Test User Input

<form name="form1"   id="form1" method="post">
<input name="field1" id="field1" type="text" value="2" onblur="validate();"/>
<input name="field1_save" id="field1_save" type="hidden" value="2" />

<input name="btnSubmit" type="submit" value="Submit" />                             
</form>
</body>
</html>

Post a Comment for "Javascript To Prevent Invalid User Input"