title: Javascript to prevent invalid user input
body: <p>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:</p>
  
  <p>When a user enters an invalid form, I display an alert and inform them that the value entered is incorrect. Crucially, the original (valid) value in the form is not changed.</p>
  
  <p>The value is only changed when the value has been validated.</p>
  
  <p>For example, suppose I want to accept only positive integers in a field.</p>
  
  <p>This is the sequence of events that describes the desired behaviour.</p>
  
  <p><strong>Scenario 1 (valid input)</strong></p>
  
  <ol>
  <li>Form loads with valid default in the input field</li>
  <li>User types in valid number</li>
  <li>Input field value is updated (as per normal form behaviour)</li>
  </ol>
  
  <p><strong>Scenario 2 (INvalid input)</strong></p>
  
  <ol>
  <li>Form loads with valid default in the input field</li>
  <li>User types in INvalid number</li>
  <li>Alert box is shown alert('Invalid value')</li>
  <li>Input field value is NOT CHANGED (i.e. the value is the same as BEFORE the user typed in the invalid number)</li>
  </ol>
  
  <p><strong>[Edit]</strong></p>
  
  <p><strong>The only problem I am facing at  the moment (i.e. what this question is seeking an answer for), is Scenario 2, action point 4. More specifically put, the question degenerates to the following question:</strong></p>
  
  <p>How do I stop the value of a field from changing, if I (somehow) determine that the value being entered by the user is invalid. This is really, all I'm trying to answer.</p>
  
  <p>I am also doing server side checks, this question is just about the front end - i.e. refusing to change a field (form text input) value if I determine that the value is incorrect.</p>
  
  <p>BTW, I am using jQuery, and would like to implement this in a manner that separates behaviour from display (I think this is what is meant by the term 'unobtrusive' ?)</p>
  
  <p>Any suggestions on how to implement this behaviour as described above, would be very much appreciated.</p>
  
  <p>PS: I dont want to use yet another jQuery plugin for this. I should be able to use jQuery + the simple javascript validation functions I have already written.</p>