I've created a javascript function that allows me to validate if one field or the other is filled (called, shockingly enough, oneortheother). Essentially, it checks if neither is filled, or both, and throws an error.
One of the fields being validated is a input type="file" field. I'm displaying below the field the existing file, so that the users can see if it's the file they want.
Is there any way to still validate via oneortheother without having a value in the input type="file"? Any kind of javascript trickery?
I'm at wits end at this point, and have a demo later today that needs this functionality, so any help would be greatly appreciated.
EDIT:
As requested, here's some examples:
<label for="pdf">Upload PDF:
<span class="fieldnote">Files of type .pdf</span>
</label>
<input type="file" name="pdf" id="pdf" class="external_form_field oneortheother_url" value="/downloads/white_papers/HigherOrderPerl.pdf" />
<label>Existing file:</label><span class="preview">HigherOrderPerl.pdf</span>
<label for="url">Link to asset:</label>
<input type="text" name="url" id="url" class="external_form_field oneortheother_pdf" value="" size="25" />
Notice that the class oneortheother_url and oneortheother_pdf are applied. This allows the validation routine to know which field to compare to. The comparison is:
if (fObj.value && fObj2.value) { }
and
if (!fObj.value && !fObj2.value) { }
I unfortunately I couldn't understand the actual question, but here's a sidebar tip:
The XOR operator can come in handy (though obscure) in cases like this:
if (fObj.value ^ fObj2.value) {
// Only one value is set, we're good
} else {
// Both of them are set or neither of them are set
}
I am not sure how your validation function works, but it seems like you could add a hidden input that holds the url of the uploaded preview file OR the value in the file input. Then you could just compare the url input with the hidden input.
But it seems likely you'll just need to write a custom validation function.
I'm not sure I understand your question completely as it's not clear to me.
You want to check this:
if (fObj.value && fObj2.value) {}
and
if (!fObj.value && !fObj2.value) {}
So why not add this in as well...
if (fObj.value && !fObj2.value) {}
or
if (!fObj.value && fObj2.value) {}
What about adding a radio button next to each option, and allowing the selected radio button to determine which option is used?
I'm not sure exactly what you're trying to do here, but you could add a hidden form field, then attach a function to both the file input and the URL inputs' onchange events, that would set the hidden field to this value.
Fundamentally I'm not even sure that the approach you're currently taking is appropriate - Firefox 3, for example, doesn't let you edit the contents of a file field directly and as far as I can tell gives you no way to "unset" a value. So once a file has been chosen, the "pdf" input will always be non-null, which with the constraints you have set (as I understand them) means that the "url" input is effectively permanently disabled. This is even worse since you give the file input an initial value so that it will never ever be null/empty string.
You may need to take a step back and think about exactly what you're trying to acheive and whether an alternative technique might be better. For example, a radio button to select between the file upload box or a URL resource, which disables and enables fields as appropriate.
Additionally, the fact that most people here didn't understand quite what you're asking even after an edit is an indication that there's something about it that's not too intuitive, and it implies that people who will need to maintain this code in future might go through a similar thing. Again, refactoring the design is probably in order, or perhaps jsut a bunch of descriptive comments.
Related
I'm trying to implement the 'placeholder' attribute on a new mobile web site. Running into an issue where if a user leaves the field blank (showing the placeholder) then that placeholder is submitted as the field value for PHP to receive and place in the database. Instead it should (I assume) be sending an empty value. This causes problems with server side validation - the receiving PHP script thinks a legitimate value has been submitted instead of an empty value which would throw an error back to the user.
I am hoping there is a quick fix to this issue.
Sample code below:
<form action="somepage.php" method="post">
<input type="text" name="yourName" placeholder="Enter your name here">
<input type="submit">
</form>
PHP sees:
$_POST['yourName'] = 'Enter your name here';
instead of:
$_POST['yourName'] = '';
The latter is what I want it to see.
Any help would be greatly appreciated!!!
* EDIT **
Here is an example form with the problem:
https://www.badgleymischka.com/mobileTest.php
Leave all fields as is (note in the source these are filled in by the placeholders, not the values). Click the "CONTINUE" button and you will see the _POST variables with the placeholder values.
Something is removing the placeholder attr text on page load on several inputs...
Based on your source, you're calling two different jQuery scripts. Delete this found near your closing <body /> tag. This may be conflicting with Foundation's included Placeholder plugin.
<script src="js/vendor/jquery.js"></script>
But this is probably the culprit: Not sure what you're trying to write here. But this looks to be the issue. See line 17 in jquery.main.js. Remove this all. I don't think it's needed and is conflicting.
// clear inputs on focus
function initInputs() {
PlaceholderInput.replaceByOptions({
// filter options
clearInputs: true,
clearTextareas: true,
clearPasswords: true,
skipClass: 'default',
// input options
wrapWithElement: false,
showUntilTyping: false,
getParentByClass: false,
placeholderAttr: 'value' // <-- ding, ding! Prob the conflictor, if not this entire function
});
}
I cannot reproduce your error. I tested it using Firefox 25 and 26, Chrome 31, IE 11, Opera 12.16 and Safari 5.1.7. And looking at the specification I don't believe that the placeholder is intended to be submitted - so you are indeed experiencing some kind of bug.
The only reason for this behavior I can think of is that you are including a (java)script in your HTML, aimed at browsers that don't support HTML5 (and the placeholder attribute). Such a script could be filling empty inputs with their placeholders, but failing to remove them before the form is submitted.
If this is indeed the case, and your problems are caused by such a script, you can solve them by either fixing the script or removing it completely. If you choose to fix the script, you'll need to make sure that inputs whose value equals their placeholder are reset to their default value.
Just stumbled across this in my own search, so if anyone else is looking for an answer to this try this:
<input type="text" name="yourName" placeholder="Enter your name here" required>
By adding "required" to the input tag the user must fill out this field before submitting.
This should work like charm but i assume since its on mobile something is different.
One solution(i am sure there is a better one) is to check it with an if.
So if the value is the same as the place holder then make it blank and then continue your validations.
Also try to put val="".
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.
So let's say i have a form where the user can add as many dogs as they want by pressing a + button.
The form is like:
Dog #1 <br/>
<input name="house[dogs][][name]" value="<?=set_value('house[dogs][0][name'])?>"/>
<input name="house[dogs][][age]" value="<?=set_value('house[dogs][0][age]')?>" />
Dog #2 <br/>
<input name="house[dogs][][name]" value="<?=set_value('house[dogs][1][name'])?>"/>
<input name="house[dogs][][age]" value="<?=set_value('house[dogs][1][age]')?>" />
On CodeIgniter, I run a form validation in order for set_value() to work as well:
$house = $this->input->post('house');
$dogs = $house['dogs'];
$i = 0;
foreach($dogs AS $dog){
$this->form_validation->set_rules("house[dogs][$i][name]", 'Dog Name', 'required');
$this->form_validation->set_rules("house[dogs][$i][age]" , 'Dog Age' , 'required');
$i++;
}
This whole thing doesn't work, How to make set_value() support array inputs like that?
Thanks in advance.
You might have to make the input name the exact same as the first parameter of set_value().
One might not be able to be [], while the other can use [0].
Very related: http://codeigniter.com/forums/viewthread/179581/ Ironically, a post I made months ago that was bumped this morning.
Also related: CodeIgniter: Validate form with multidimensional POST data
<ignore>
To make a long story short, Codeigniter does not handle indexed field names very well by default.
To simply repopulate the input and work around set_value()'s shortcomings, you can try something like this:
<?php
$value = isset($_POST['house']['dogs'][1]['age']) ? // was the value posted?
form_prep($_POST['house']['dogs'][1]['age']) : // if so, clean it
''; // if not, leave empty
?>
<input name="house[dogs][1][age]" value="<?php echo $value; ?>" />
Since you're probably using a loop to output these, I don't think it will be too much of a bother. You could populate a separate array of values and read those instead if you wish, you get the idea. set_value() automatically runs form_prep(), so that's why I added it.
I'm not too sure about the validation. You may have to do the validation yourself, which while bothersome, shouldn't be too difficult. Remember you can always run the validation methods manually. Example:
if ($this->form_validation->valid_email($this->input->post('email')) {}
You may want to just take the easy way out and change your field names to use a single index, like dog_age[], which I believe will make the validation easier for CI to handle. Best of luck, hoping for a fix one of these days in CI core.
</ignore>
EDIT: I have no idea how this escaped me, but apparently validation and set_value should in fact work as expected - not sure if this was a recent change or if the issue never really existed. I definitely remember having issues with it before, and the linked posts suggests others are too. Check out this answer though:
CodeIgniter: Validate form with multidimensional POST data
I tested it (running 2.0.2) and it does in fact work. I don't see anything in the change log, but I did test it and it did work. Make sure your on the latest version and try again perhaps, or let us know if I'm missing something here.
Like your other answer says, you probably just have to explicitly index the field names like name="house[dogs][1][name]" instead of name="house[dogs][][name]".
Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.
For the past few years I've focused on back-end development so my javascript & css skills are lacking. I'm volunteering as a webmaster for a site and would like to spruce up the form validation (currently there is none).
My problem:
Basically I have one form with a few name fields, an email address and a phone number. When the form is submitted I validate all fields. If data is invalid I would like to change that field's label color to red (similar to struts validation). What's the easiest way to do this?
Edit: I also have back end PHP validation. I'm looking to make it prettier and more user-friendly on the front-end. The PHP validation is located on a different server. If the validation fails on the back-end it displays a message and the user is forced to use the Back button. I'm hoping to re-direct back to the original page and display the invalid fields.
when you're building the page server-side, mark all the fields with errors in them:
<input type="text" name="phone_number" class="error_field">
555-121
</input>
Then in the page's CSS include an entry like:
input.error_field { color: #FFF; bgcolor: #C00; }
(The period's a "class selector", means it applies to all inputs with the class attribute "error_field". If you're already using classes for your input tags you can give elements multiple classes, just use spaces to separate.)
If you want to know what kind of code Struts is producing to color the page, one easy way is to use the Firebug extension for Firefox.
Assuming that the label is in the same level of the DOM hierarchy as the input and that it is right next to the input in the markup, you can do something like this.
First of all, some example HTML:
<html>
<body>
<form onsubmit="return validation()" action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" value="" id="name" />
<label for="email">Email:</label>
<input type="text" value="" id="email" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
As you can see, all of the inputs are preceded by a label with the correct for attribute.
Now for the Javascript, which would go in the head:
<script type="text/javascript">
function validation() {
//So we have a validation function.
//Let's first fetch the inputs.
name = document.getElementById("name");
email = document.getElementById("email");
//The variable error will increment if there is a validation error.
//This way, the form will not submit if an error is found.
error = 0;
//Now for validation.
if(name.value.length < 6) {
//We've found an error, so increment the variable
error++;
//Now find the corresponding label.
nameLabel = name.previousSibling;
//If we found the label, add an error class to it.
if(nameLabel && nameLabel.for = name.id) {
nameLabel.className = "error";
}
}
///////////////////
//Do the same with the email...
///////////////////
//Now, if there are no errors, let the form submit.
//If there are errors, prevent it from doing so.
return (error == 0) ? true : false;
}
</script>
Now just add some CSS:
<style type="text/css">
.error {
background-color: red;
}
</style>
Edit -- I guess you didn't want this sort of solution, but in case you want it to validate before going to the server, here you go. :)
Struts validation is happening on the server side; JavaScript validation runs on the client. The distinction is important, because server-side validation still works even if your client turns off JavaScript in the browser (and ~10% of people reportedly do).
Best to have both if you can.
You can put this together yourself, as others have suggested. But I seem to remember that Struts has its own JavaScript validation. It can be configured to generate JavaScript functions, which perform the same checks that are done on the server side. Check the documentation -- this may be a fast way to get started, although it may not be as customizable as you want.
I definitely haven't used struts before, but I do a lot of form validation with and without javascript.
In my opinion, you should always have both javascript and server-side validation, so it should work for everyone.
Server-side, you should do something like glaziusf.myopenid.com mentioned, just add a class to the element which shows it in red.
In javascript (and ajax), just add the same class to the element that you'd use server-side, but dynamically.
I'd recommend you learn a JavaScript framework like JQuery or Prototype. JQuery helps you to obtain values out of filtered-elements, modify their CSS, add visual effects, etc. really easily.
I don't really understand the PHP logic of your site, but you can put a validation in the same page if the action submits to itself, although I don't know if it's a good practice.
For example, you put the following at the top:
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
//field validation code...
To redirect with PHP you just say:
header("Location: THE_PAGE.php");
Although you shouldn't have outputed anything before that. You could probably pass a parameter back to your page (i.e.: THE_PAGE.php?valMsg=1) to tell it to show validation messages, or something of the sort.