Javascript to prevent invalid user input

I wrote 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 behavior:

When the user enters an invalid form, I issued a warning and informed them that the entered value is incorrect. Actually, the initial (actual) value in the form does not change.

The value changes only after checking the value.

For example, suppose I want to accept only positive integers in a field.

This is a sequence of events that describes the desired behavior.

Scenario 1 (actual input)

  • Loading forms with a valid default value in the input field
  • Types of users in a valid number
  • The value of the input field is updated (in accordance with the behavior of the normal form)

Scenario 2 (INvalid input)

  • Loading forms with a valid default value in the input field
  • User types in INvalid number
  • A warning is displayed in the warning field ("Invalid value")
  • The value of the input field is NOT CHANGED (that is, the value is the same as before the user who dialed an invalid number)

[change]

The only problem I am currently facing (i.e. what this question is looking for for an answer) is scenario 2, step 4 of the action. In particular, the question degenerates into the following question:

How to stop changing a field value if I (somehow) determine that the value entered by the user is not valid. In fact, everything I'm trying to answer.

, , .. ( ), , .

, jQuery , ( , ""?)

, , , .

PS: jQuery. jQuery + javascript, .

+3
1

js, / ? , , , js, , .

, , , , .

EDIT:
, () , . , , , , , , . .

<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>
+1

Source: https://habr.com/ru/post/1732747/


All Articles