jQuery validate max value on Form Submit - javascript

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/

Related

In a dynamically changing fields using jquery same field gets posted twice

I'm working on a form where I have a text field which will be changed on radio button selection.
$("#id_radio1").click(function() {
$("#multi_language").hide();
$("#single_language").show();
});
$("#id_radio2").click(function() {
$("#single_language").hide();
$("#multi_language").show();
});
Say suppose id_radio1 and id_radio2 are two radio buttons and selecting each changes the form fields differently. Now I was able to do it successfully.
My problem is when I submit the form after single language button is clicked the values are stored as multi as the values of the multi language hidden fields are submitted overridding the values of first.CAn I disable the other field without interference of the same on submission.
How can I correct this?
I'm new to such problem. I want the field to be submitted only once.i.e, if single language field is selected single should be posted and not multi(as it is working now) and when multilanguage is selected multi should be posted.How can I correct this now with the following code.
Fiddle
I have other fields common for both single and multi language in the same form as well, whose values are not changed on submission
Now, in the console I see there are two posts for the same fields in the response i.e. one for single language and other multi language.
You can format your html code as below just if you want to pass the value of the checked field to some other script
<form method="post">
<input id="id_radio1" type="radio" name="name_radio1" value="single" />
<label for="id_radio1">Single Language</label>
<input id="id_radio2" type="radio" name="name_radio1" value="multi" />
<label for="id_radio2">Multi Language</label>
<input type="submit" />
</form>
and in your Jquery Code, you can do this
$("form").on("submit", function(e) {
e.preventDefault();
console.log($("input:checked").val()); //do whatever you want with the checked value
})
Fiddle
You can use the disabled attribute to prevent an element from being sent like so:
$("#id_radio1").click(function() {
$("#multi_language").attr('disabled','disabled').hide();
$("#single_language").removeAttr('disabled').show();
});
$("#id_radio2").click(function() {
$("#single_language").attr('disabled','disabled').hide();
$("#multi_language").removeAttr('disabled').show();
});
Since they are no hidden fields but just hidden by css it should prevent it from being submitted
Why not just have one text input, then in your server-side code simply check which radio button was selected and set the value of the server-side variable accordingly before committing data.
e.g. In PHP for instance:
$language = $_POST['language'];
if($_POST['name_radio1'] == 'single'){
some_function_committing_single_language_value($language);
} else {
some_function_committing_multi_language_value($language);
}
Or have one text input and set the form's onsubmit handler with a Javascript function to insert a hidden field with a name such as 'language_single' or 'language_multi' based on the radio button selection, and set that hidden input's value to the textfield's value.

Can two form inputs have the same name if one is disabled?

I have an address form and I want to have a select box for states if the country is the U.S. and change it to a textbox if it's a foreign country so that the state/province can be typed in.
I generate the code in PHP (such as the states select and country select) and I was thinking of outputting both the select and textbox and initially hiding and disabling the textbox, then if the user changes the country unhide and enable the textbox and hide and disable the select.
My question is, is it valid if both inputs have the same name, assuming one of them will be disabled when the form is submitted?
As a bonus question, is there a better way of doing this?
Yes, it is possible and it is the best way to do this, since disabled inputs are not sent along in the request and it generates a valid and semantic HTML.
As show in w3:
When set, the disabled attribute has the following effects on an element:
Disabled controls do not receive focus.
Disabled controls are skipped in tabbing navigation.
Disabled controls cannot be successful.
[...]
In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.
Assuming you use jQuery, you could do something like this:
HTML:
<select id="countries">
<option>Countries</option>
</select>
<select id="states" style="display: none"> <!-- States in US -->
<option>States</option>
</select>
<textarea id="address" style="display: none">
</textarea>
JS:
// Cache states list and address box beforehand so we don't have to query every time.
var $states = $("#states"),
$address = $("#address");
$("#countries").change(function () { // Bind to change event for checking if US selected
var isUnitedStates = $(this).val() == "United States";
if (isUnitedStates) { // US is selected, show States
$states.attr("id", "address").show()
$address.attr("id", "_address").hide()
} else { // US is not selected, show Address box
$states.attr("id", "_address").hide()
$address.attr("id", "address").show()
}
})
This is not very convenient but if you really want to make sure, this is an option for you.

Validate a textbox when option is selected

I'm creating a registration form with ColdFusion. One of the requirement is for user to select a value from a drop down. When one of the option is selected, the next textbox field need to be fill in so this field becomes required field. If user does not select any option from a drop down then this texfield can be left blank.
I'm not good with Javascript, is there a way to get some free sample?
Here is my form fields:
<cfselect name="OtherContact" class="inputSelect">
<option value="">--- Select other contact ---</option>
<option value="HomePhone">Home Phone</option>
<option value="HomeFax">Home Fax</option>
<option value="HomeEmail">Home Email</option>
</cfselect>
<cfinput type="text" name="OtherContactId" value="#Form.OtherContactId#" class="inputText">
What you need to do is before the form is submitted to see if the dropdownlist selected index is different from 0, if it is, then the text of your textbox must be different from an Empty String. This is an example:
// this is the javascript function that will make sure your criteria is found, if it does, it will return true, false otherwise
function validateSubmit(){
var OtherContact= document.getElementById('<%=OtherContact.ClientID%>')
if (OtherContact.selectedIndex !== 0){
if (document.getElementById('<%=OtherContactId.ClientID%>').value === ""){
return false;
}
}
return true;
}
So, before you submit (or do whatever you want to do after the validation), you can do this:
// function that submits
function submit(){
if (validateSubmit()){
// your code in case validation is passed.
}
else{
// your code in case validation is not passed.
}
}
Good luck.

Iterate through all form elements irrespective of their type

I am busy with a form manager for one of our clients. The general idea is that forms will be built for the individual departments and I want to create a micro system which will handle validation etc for the form without redoing too much work. As automated as possible.
My first major task is that I want to on clicking the submit button, iterate through the entire form and based on specific credentials and validation rules validate the form before it gets sent to the server. I have seen a number of posts related to getting example all the input fields in a form, but I am looking for a solution which will iterate through the entire form and it's contents and then do validation on specifically all of the form elements (which includes select boxes, input boxes, text boxes etc).
I could do this separately, but I would preferably like the validation to be done top - bottom so if the first field is example a select and the next is an input field, it should iterate through the form from top to bottom so that I can output errors according to that.
// Sample code:
$(document).ready(function() {
$("#main_submit").click(function() {
// Select all of the form fields here and iterate through them ...
});
});
<form name='test_form' method='POST' action=''>
<div>
<label for='title'>Title</label>
<select name='title'>
<option value=''>Please select ...</option>
<option value='MR'>MR.</option>
</select>
</div>
<div>
<label for='full_name'>Full Name:</label>
<input name='full_name' type='text' />
</div>
.....
</form>
Use the jQuery :input selector:
jQuery("form :input");
Description: Selects all input, textarea, select and button elements.
http://api.jquery.com/input-selector/
Try this:
//loop through all input elements
$("form :input").each(function(){
var thevalue = $(this).val();//the value of the current input element
var thename = $(this).attr('name');//input name
var thetype = $(this).attr('type');//input type
});

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

Categories