How to Completely Prevent Web Form Input Text Item change

1.1k Views Asked by At

I have this simple web-form

<form id="MyFormDiv" method="post"> 
     <input type="number" name="cmp_no" id="id_cmp_no">
     <input type="text" name="cmp_lname"  maxlength="40 id="id_cmp_lname">  
     <input type="submit" name="submit" value="Save" id="submit-id-submit">
</form>

and this form will be used for both add and update.

When insert I have no problem, but when update I don't want to allow user to update or change the value of item which its id= "id_cmp_no"

I used javascript code to set its readonly property to true but that was not the 100% solution, because user can use browser inspect tool and see page source and change it's value before submitting the form, and therefore the readonly property is not useful.

Can I override it's onchange event to prevent change of it's value even if the value changed from page source using inspect tool.

Any one can help, thank you in advance

2

There are 2 best solutions below

0
Anis R. On

If a user is skilled enough to open dev tools and change values from there, chances are they can also alter any JS code that prevents editing the readonly value.

So, there is no substitute to proper server-side validation.

You could check that the value is not being altered from the form's onsubmit event handler (see below), but keeping in mind what I and many commenters stated above.

$("form").on("submit", function(e) {
  //check value of the input
  if(this.someInput.value != 1) {
     //do something here
     //return false; if you want to block submit
  }
  return true;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="form">
  <input type="number" name="someInput" readonly value="1"/>
  <button type="submit">Submit</button>
</form>

1
Saddam On

There is nothing that stops a user from changing values in browser, u can try solutions given in the above answers but be cautious user can dig out number of ways to do so like by using firebug/inspect element/ what ever..

What we can do is checking our values on server side and prompting user if they mismatch.

Shouting again ..

Never trust/depend on client....