Javascript to prevent invalid user input - javascript

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 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.
The value is only changed when the value has been validated.
For example, suppose I want to accept only positive integers in a field.
This is the sequence of events that describes the desired behaviour.
Scenario 1 (valid input)
Form loads with valid default in the input field
User types in valid number
Input field value is updated (as per normal form behaviour)
Scenario 2 (INvalid input)
Form loads with valid default in the input field
User types in INvalid number
Alert box is shown alert('Invalid value')
Input field value is NOT CHANGED (i.e. the value is the same as BEFORE the user typed in the invalid number)
[Edit]
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:
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.
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.
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' ?)
Any suggestions on how to implement this behaviour as described above, would be very much appreciated.
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.

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>

Related

How to see if a form element was not posted

I have a form where e-mail is optional. To control that there is a checkbox. If that checkbox is unchecked, the e-mail textbox would be disabled and therefore not posted on submit. However, on the next page, if I have code like as shown below, it gives me an error if the e-mail textbox is disabled.
if (isset($_POST['submit']))
{
$_SESSION["email"] = $_REQUEST['YourEMail'];
....
}
To get around that problem, I progammatically enable a disabled e-mail textbox just before submitting besides setting its value to an empty string. The code for that is shown below.
document.getElementById('YourEMail').disabled = false
document.getElementById('YourEMail').value = ''
However, one annoying problem remains, which is that, if the user goes back to the original page, the e-mail textbox is enabled, since I enabled it problematically just before submitting the form. However, I want it to be disabled in that case. How, can I achieve that? Alternatively, how in the next page, I could see that e-mail box was disabled and therefore not even try to read $_REQUEST['YourEmail']?
if the field "#YourEMail" is optional you can check if exists in PHP. There is no need for enable/disable the field using JS.
if (isset($_POST['submit']))
{
if (isset($_REQUEST['YourEMail']) && !empty($_REQUEST['YourEMail'])){
$_SESSION["email"] = $_REQUEST['YourEMail'];
}
}
You can test it like this using a ternary:
(isset($_REQUEST['YourEMail']) && !empty($_REQUEST['YourEMail'])) ? $_SESSION["email"] = $_REQUEST['YourEMail'] : FALSE;
This would only set the session variable if the request variable is set.

How to set prefilled input field active with Jquery/javascript?

I'm using a calculator widget where I can enter random values into an inputfield and then the widget automatically calculates when clicking the "go"-button.
Now I want to insert/prefill the value into this input field, since the value which needs to be calculated comes from a server. The issue though is, that this input field apparently only reacts on keypress. I tried to do this:
$('input[name="value"][data-type-money]').val('150.000').focus();
and
$('input[name="value"][data-type-money]').val('150.000').select();
which prefills the input field with the desired value but when I click the "go" button the calculation fails as long I dont enter the value manually into the input field. So, in the end my solution does not work.
Does anyone know how I can solve this?
If data changes frequently you can also use the setInterval function:
<input name="value" data-type-money="money">
setInterval (function(){
var moneyValue = "150.000";
$('input[name="value"][data-type-money]').val(moneyValue);
},1000);
fiddle here: http://jsfiddle.net/85pbnnu1/
or you can just do:
$(document).ready(function(){
$('input[name="value"][data-type-money]').val('150.000').change();
});
Edit, Updated
the input field is -
and reacts only on keypress, I mean when value is entered manually
If input value property cannot be changed , try replacing the element in DOM with value set at html using .replaceWith()
$('input[name="value"][data-type-money]')
.replaceWith("<input name=value data-type-money type=text value=150.00 />")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input name="value" data-type-money type="text" />

How to define default values for HTML form elements without populating the field?

I have a huge form with many text boxes. Not all are mandatory but I dont want it to send undefined to my backend since many are of type integer and float.I need to define default values for all of them but I don't want the users to have to delete the default values before entering theirs everytime. The default values show up if I do value="defaultVal" in the <input>...</input> tag. I tried providing placeholder="..." but still value overrides placeholder. Any suggestions to achive this?
you can set the default value as you have been, and then just clear the input field onFocus, so that the user can enter into a fresh slate
You can try this:
<input type="text" onfocus="if(this.value == 'value') { this.value = ''; }" value="value" />
Source code

jQuery validate max value on Form Submit

I want to validate a form, when it gets submitted. I need to check the following things:
Whether the user has selected any option from the dropdown.
Whether the user has entered a value larger than the max-value
If any of this conditions is not matched, I want to show an error message in a modal window...
How can I achieve this behaviour? Below is a code snippet:
//This function sets max value, based on selected option's data-max
$('select').change(function(e) {
var selectedIndex = $('select').prop("selectedIndex");
var selectedOption = $('select').find("option")[selectedIndex];
$('input[type=number]').attr('max', $(selectedOption).data('max'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="./cart_update.php">
Select Size:
<select size="1" name="options" class="selectsize">
<option value="">-- Select --</option>
<option value="30" data-max="50">30</option>
<option value="31" data-max="50">31</option>
<option value="32" data-max="40">32</option>
<option value="33" data-max="50">33</option>
<option value="34" data-max="50">34</option>
</select>
Quantity
<input type="number" class="cart_qty" name="product_qty" size="1" value="1" min="1" max="100" />
<button class="orange medium full add-to-cart" type="submit">Add To Cart</button>
</form>
As you didn't give any information on whether you validate the form data within the backend as well, I assume that you don't.
Validating form data only on the client side (i.e. within the client's webbrowser) is not advisable. That is because clients can easily manipulate the javascripte code you're using to validate data. By doing so, it is possible to import fraudulent data into your application (and many many more bad things could happen).
Validating data on the client side should only be used to give your users a quick feedback on whether the entered information is correct and in accordance to your definitions. Real data validation, before you further use it within your application (i.e. store it within a database, or what ever), should happen on the server side.
I advise you reading these articles to further deep dive into the topic of data validation:
Data form validation (mozilla.org)
If you're using PHP as a server-side language: PHP 5 Form Validation (w3schools.com) or if you're using javascript as a server-side language: How to Easily Validate Any Form Ever Using AngularJS(thecodebabarian.com)
Web Form Validation: Best Practices and Tutorials (smashingmagazine.com)
Coming to your question (and assuming you read the articles and now want to validate the data only for the user's sake), here's kind of a commented working code snippet:
$(document).ready(function () {
// Whenever your form is submitted, execute this function
$('#ourForm').submit(function (e) {
// Prevent the browser from executing the default behaviour -> submitting the form
e.preventDefault();
// Now check the user's entered information for accordance to your definitions
// #1: Check whether any checkbox is ticked
var checkBoxValue = $('#ourCheckbox').val();
// If checkBoxValue is undefined, there is no checkbox selected,
if (!checkBoxValue) {
// There is no checkBox ticked, throw error
alert('Please select a checkbox!');
return false;
}
// #2: Check whether entered value is smaller than the data-max field of the selected checkbox
// Receive the user's entered value
var enteredValue = $('#ourInputfield').val();
// Receive the max value specified by you from the data-max field
var maxValue = $('#ourCheckbox option:selected').attr('data-max');
// If the entered value is bigger than the max-data value
if (enteredValue > maxValue) {
// The entered value is bigger than the data-max field of the selected checkbox, throw error
alert('Your entered value is to large, please choose a value lower than ' + checkBoxValue.value);
return false;
}
// Validating your form data is finsihed, go on with the real work
alert('Your data looks fine, whoooo!');
});
});
Here's a working JSFiddle: https://jsfiddle.net/77v1z18v/1/

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Categories