I am using PHP codeigniter framework. I used jQuery validations like below
$('#form_id').validate({
rules here,
messages here
});
I have question related to security. If I remove form id by inspect element then jquery validations dont run. I know it can be handle by using client side validations. but just thinking if there is any other solution so user can not remove form id
I don't think there's a way to stop someone from deleting the HTML, but you could check to see if the Form ID and Inputs are there first, before the rest of your validations..
Something like:
$("form").submit(function(event){
if ($(this).attr("id") != 'form_id') {
event.preventDefault();
alert("Missing or Altered Form ID");
}
if (this.FirstName === undefined) {
event.preventDefault();
alert("Missing Input Fields");
}
});
**FirstName is the name of the input:
<input type="text" name="FirstName" value="Mickey">
Of cause client side validation is must but when it comes to the "Security" do not trust the user. As you mentioned user can send the any data as validated data. So the best solution is to validate the same data in the back-end/ server side validation.
In Codeigniter comes with nice validation library you can see here
For your point
is any other solution so user can not remove form id
by assuming you are asking this related to Java-scripts the answer is NO. Because Java-script runs on the client side / on the users browser and there are ways to change or remove the form ID so that we are out of reach controlling the user editing the our script so we cannot assure what we are getting from the user and the solution is do the back-end validation as I mentioned above and hope this will helps.
Related
I use some jQuery on a current gravity form. However, when I submit the form and it comes back with bad validation, I lose some of the jQuery targets.
I'm curious how I can swap out $(document).ready(function() { with something that will call my jQuery once the fields are reloaded with bad validation.
I've tried $("#gform_submit_button_1").click(function() { however, that's too soon. It needs to happen when the new fields come back from ajax.
There is actually a hook provided for use here: gform_post_render
This jQuery hook is fired every time the form is rendered to allow custom jQuery to be executed. This includes initial form load, going to the next/previous page on multi-page forms, form rendered with validation errors, confirmation message displayed, etc.
jQuery(document).bind('gform_post_render', function(){
// code to trigger on AJAX form render
});
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/javascript/gform_post_render/
For some reason Gravity Forms still hasn't added a jQuery hook for failed form validation. What they recommend doing is checking for the existence of div.validation_error.
jQuery(document).on('gform_post_render', function(e, form_id) {
if ( jQuery('div.validation_error').length > 0 ) {
console.log('Form validation error.');
}
});
You'll notice I'm not specifying a parent when I check for the validation error element: jQuery('div.validation_error'). If you have multiple forms on the page this would cause issues. The form_id parameter that is returned contains the form's ID in the database (e.g. 1, 2, 35, etc.) but I'm not sure if this value matches the forms ID in the HTML, e.g. <form id="gform_1">. If it does match, then it's good practice to specify the parent, so you could do:
if ( jQuery('div.validation_error', '#gform_' + form_id).length > 0 ) {
Maybe somebody else could weigh in and let us know if the form's HTML ID will always match the form's database ID.
Gravity forms does supply a gform_confirmation_loaded hook, but I don't think this will work in your case since it's not loading the confirmation, but the error state form. They don't have a hook for this but I've had success using jquery delegated events. I use the .gform_wrapper as my first selector and then target the fields I want to actually target.
See this documentation for more info:
http://api.jquery.com/on/#direct-and-delegated-events
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/filters/gform_confirmation_loaded/
One solution is: catch the submit event and start a interval that checks your form for changes and then calls your function:
$('#your-form').submit(function(){
html = $('#your-form').html();
iv = setInterval(function(){
If($('#your-form').html != html){
yourfunc();
clearInterval(iv);
}
}, 200);
});
function yourfunc(){
//your stuff
}
This is however not very neat and it will only work if the html is actually changed after the Ajax call.
I've been trawling through all the suggested posts for this topic but can't seem to find a solution that either works for me or I quite understand.
I am just trying to do a simple honeypot which checks if a hidden field is filled in by bots and breaks the form if so. My problem seems to be when it comes to using AJAX to see if the PHP value cleared. Hope that makes sense as I'm not well versed in coding languages.
My original idea was to disable the submit button for any bots that fill out the field. However seeing as the field is blank straight out the form loads the submit button and the point is lost.
This is the part of the form checking for the bots:
<!-- THE HONEYPOT -->
<li id="artificial-detect">
<label for="artificials">If you see this, leave this form
field blank and invest in CSS support.</label>
<input name="artificials" type="text" value="">
</li>
<!-- /HONEYPOT -->
<?php
$spam = $_POST['artificials']; // This is our Honeypot field
if($spam) { // If the Honeypot field has been filled in
die("No spamming allowed bitch!");
} else { ?>
<li class="last">
<input class="submit" type="submit" name="submit">
</li>
<?php } ?>
I don't understand what to do now:
jQuery.('#salesforce-crm-form .submit').click(function(){
jQuery.ajax({
// Get PHP function that determines whether the honeypot has been snatched.
});
});
I am using an external URL for the action="" so I thought maybe that could only be inserted if the PHP returns clean of bots.
You cannot do the things in the order you think.
First PHP runs to deliver your form.
Then the browser acts, displays the form to the user. He might enter data and send it back.
Then PHP is on again, checking the form values.
You pretty much have the code you want to check if the honeypot field is filled. You should not try to use AJAX, because this PHP check can only be taking place after sending the form. Simply don't do what the form is intended to do if you detect spam.
BTW, Bots dont press submit buttons. Bots send Request based on parsing forms, disabling all Javascript.
[EDIT]
If your form goes to an external URL, then you cannot control any spam detection. Because bots do not use Javascript, anything on this level will not work, either, but thats what you are trying to do.
Only thing that will work is to NOT send the form to the external URL directly, but to a PHP script on your server that will check for spam an then send it to the original destination. Don't know if this will mess up anything else because now it is not the users browser sending the form, but your server. If there is any detection and/or usage of request metadata on that side, you are interfering with this.
Put default value in honey pot input and ask user to delete it before post. Also there is no use for disabling submit button:) Bots do not work this way, they will simply submit form without clicking anything.
If you change the type of the input box to hidden, and give it an ID, like so
<input name="artificials" type="hidden" id="honeypot" value="">
then users will not be able to see the input but bots will fill it in.
Then in your javascript, using jquery you can check for a value like so
var honeypot = $('#honeypot').val();
if(honeypot == '' || honeypot == null) {
// Call ajax function
}
Note, that has not been tested and is only an example.
Is there a way to make a field required for form submission?
I can use HTML, Javascript or PHP to do this - whichever works.
I want to ensure that a form is not submitted with a blank value. Also it would be nice if I could make it so that users HAD to input values into certain fields.
EDIT: I don't really want to use jQuery at the moment as I'm not sure that my boss wants me to use jQuery.
Tried to do this:
<script type="text/javascript">
$('addorg').submit(function(){
if($('orgname').val()==""){
alert("Organization Name must be Filled");
return false;
}
})
</script>
And here's the HTML it is working on:
<form name="addorg" action="addorg.php" enctype="multipart/form-data" method="POST">
<div id="orgdiv"> <fieldset><label for="orgname">Organization Name</label>
<input type="text" name="orgname" id="orgname"/>
</fieldset>
</div>
This is for client-side validation. I can handle server-side validation, my PHP is far better than my Javascript or jQuery.
The client-side validation did not seem to work.
Nothing will ever prevent a form from being submitted to your web server. You can submit anything you like using tools like Curl. Therefore, you must always validate on the server. For normal users, you can put JavaScript in your page that blocks submitting invalid forms.
Therefore:
Is there a way to make a field required for form submission?
No.
I want to ensure that a form is not submitted with a blank value. Also it would be nice if I could make it so that users HAD to input values into certain fields.
You cannot. However, #Nicolas's answer shows how you can add client-side validation to block typical users from submitting the form and server-side validation to block everything else. His approach is correct.
You can do this in either JavaScript or PHP. JS is more user friendly and easier to code, but can be bypassed by determined users. It also may not function on some browsers or with some settings allowing users to continue as if there were no validation, but those cases are usually rare. I would recommend a JS solution unless this is a corporate website or has no room for error.
You can do this by modifying your form tag with an onSubmit function:
<form action="whatever" method="post" onSubmit="checkStuff();">
<input id="field_1" name="field_1"...>
You then need to create that function and place it in the head of your page. It should read something like:
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if (document.getElementById('field_1').value == '') formOkay = 0;
...
// Let the user know something is wrong somehow. An alert is easiest.
alert('fill out everything, ya goof!');
// If you return true the form will submit. If you return false it will not.
if (formOkay == 1) {
return true;
} else {
return false;
}
}
Note that your inputs must have an id attribute for this approach to work (though it's possible to modify my code to work with names too). I would make the id the same value as the field name. You can add additional checks for more fields where I placed the ellipsis. This code could be written more efficiently and cleanly, but I thought this approach would be easiest to understand and modify.
This is off the top of my head and hasn't been tested, but should get you working down the right track. If you have additional questions, please let me know.
EDIT:
I just wanted to follow up to agree with others that if you have the time and inclination, or this is a work related issue, you should validate both ways. JS provides a better, more user friendly method, while PHP insures nobody can just circumvent the JS to break your rules.
I don't know PHP, but your pseudo code would be something like this:
if field_1 = "" then
// Option 1
Print("Please press back and fill out field 1!")
AbortPage()
// Option 2
Redirect("form.php?error=Please fill out field 1&[other form values]")
end if
In the case of option 2 you would modify the form page to detect url variables and place them into the inputs. You would also modify it to look for a url variable called 'error' and display the contents if found.
Javascript should do it easily. Here's an example in jquery.
<input id="required" type="text />
Then, in your javascript library, you have something like:
if($("#required").val().length!=0)
{
formsubmit();
}
else
{
alert("You left the required field blank");
}
$('form').submit(function(){
if($('thisemptyfield').val()==""){
//do stuff
return false; //will cancel form submission
}
})
Makes that if thisemptyfield is empty, the submission of the form is cancelled. I encourage putting up a flag telling your user to fill in the field before submitting. Because with that code only, nothing will happen on the page. It just wont submit until the form is submitted with a value in the field.
Edit: This is using jQuery.
I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert() popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert() popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
On your form add something like this
<form name="frm1" onsubmit="InputChecker()">
Then in javascript
<script type="text/javascript">
function InputChecker()
{
if(document.getElementById({formElement}) != '') { // not empty
alert("This element needs data"); // Pop an alert
return false; // Prevent form from submitting
}
}
</script>
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
Attach an onsubmit event to the form, and return false; to stop the submission if checks fail.
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
You have a number of options when it comes to client side validation. This is just one.
<form id="tehForm" method="post">
<input type="text" id="data2check" >
<input type="button" id="btnSubmit" />
</form>
<script type="text/javascript">
function submit_form(){
if(document.getElementById("data2check").value!="correct value"){
alert("this is wrong");
}else{
document.getElementById("tehForm").submit();
}
}
</script>
For a more indepth example check out this link
I think I got a classic problem but I was not able to find a working solution so far.
I have got a form , the user clicks "Send" and everything works fine using a PRG pattern and doing both client-side and server-side validation.
The problem arises when any user (let's assume he entered valid inputs) clicks more then once quickly before the server script ends its execution...
I do not get any duplicated entry because I took care of that but the browser does not go to my "thanks for submitting page".
Instead it re-submits the same page with the same values and what I get are the custom errors I set to warn the user he is trying to enter details already stored in the database. The details sent in the first place are all in the database but the user has no chance to know that.
I tried to disable the submit button on a submit event using jQuery but in that case the data are not submitted.
HTML
<div id="send-button-container">
<input id="send-emails" type="submit" name="send_emails" value="Send"/>
</div>
jQuery
$(document).ready(function(){
$('#mail-form').submit(function(){
$('#send-emails').attr('disabled','disabled');
});
});
I am wondering if I can force a submission using Javascript after disabling the button and also how to deal with UAs with Javascript disabled
Thanks in advance
Depending on server-side language, the submit button being disabled could cause problems. This is because disabled elements are not POSTed to the server. Languages like ASP.NET require the button value to be submitted so it knows what event handler to fire. What I usually do is hide the submit button, and insert a disabled dummy button after it, which appears identical to the user. Then in your onsubmit handler, you can return false and submit the form programmatically...
$('#mail-form').submit(function(){
var btn = $('#send-emails');
var disBtn = $("<input type='button'/>").val(btn.val()).attr("disabled", "disabled");
btn.hide().after(disBtn);
this.submit();
return false;
});
Contradictory to the other up-voted answers, please note that you do not need to explicitly return true from your submit handler for natural form submission: http://jsfiddle.net/XcS5L/3/
I assume this means you are depending on the value of the submit button to service the request? That is you are checking
$_REQUEST['send_emails'] == 'Send';
This is not good practice. You should never depend on the value of the submit button because that is the just what is displayed to the user. Instead, you should add a hidden input that contains the event you want to fire. After the form is submitted, you don't need to care what the value of the submit button is and you can disable it. All other non-disabled data in the form is still submitted.
You can indeed force the submission after disabling the button.
$(function () {
$("#mail-form").submit(function () {
$("#send-emails").attr('disabled', 'disabled');
window.location = '?' + $("#mail-form").serialize() + '&send_mails=Send';
return false;
});
});
Server side set a $_SESSION variable that keeps track of the last time they made a submission and block submissions within a certain time.
<?php
session_start();
if (isset($_REQUEST['send_emails'])) {
if (isset($_SESSION['mail_sent'])
&& strtotime($_SESSION['mail_sent']) < strtotime('5 seconds ago')
) {
redirect_to_thanks();
}
do_post();
}
function do_post() {
if (do_validate()) {
$_SESSION['mail_sent'] = time();
redirect_to_thanks();
}
else {
yell_at_user_a_lot();
}
}
?>
You have to return true; You could try this if u want a simple button to submit the form.
$(function(){
$('#submitID').one('click',function(){
$('#formTobeSubmitted').submit();
$(this).attr('disabled','disabled');
})
});
On server side, generate a random number into each form, store the number when the form is submitted, and discard the submit if that number has already been stored earlier. When the user has disabled javascript, this is the best you can do. (Concurrency issues can be tricky as the two identical requests are handled at the same time - make sure you use some sort of locking mechanism, such as a table with a unique field or the flock() command in PHP.)
On browser side, just set a flag when the form is submitted, and discard all later submits:
$('#mail-form').submit(function() {
if ($(this).data('submitted') {
return false;
} else {
$(this).data('submitted', true).addClass('submitted');
}
});
You can use the submitted class to make the buttons gray or something. This has a few advantages to simply disabling them; Josh already said one. Another is that Firefox likes to remember disabled states when you hit refresh, which can cause your users getting stuck in certain situations.