How to cause a form field to be required - php

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.

Related

Removing form id using inspect element removes Jquery validations

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.

Onblur or onchange check, using a php function in a registration form

I would like to be able to check the text in a text-box after it has changed, and report what is wrong.
It is for a registration form.
This is a part of register.php where
<form action"" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p><input name="username-field" type="text" onblur="someFunction()" /><span id="UsernamehelpText"> </span>
</li>
</ul>
</form>
Then I would have a registerfunctions.php where i would store all the functions for checking lenght,char,maybe regex etc.. Its not really that important what functions i call. I just don't know how to call them.
Form what i have seen the span is where u post the errors, but if there is any other option im open for it, all i want is to be able to post the erorr text in the same line as the text-box
I have checked JavaScript and AJAX, but I am pretty new in this and don't really understand how it works.
After discussion in comments I understand what you want.
First, an explanation. There are two places where validation occurs: In your frontend (your web page) and in your backend (in the PHP script that saves the posted values). Anything that you really don't want to save - for example unescaped SQL strings, too-long fields, and so on - has to be validated in PHP, because it is trivial to get around Javascript validation. For example, nothing is stopping someone from sending a POST to your server containing illegal values without even bothering to visit your webpage.
Even though you need to perform validation in the back-end, it's still user friendly to do the same validation in the front end, so the user doesn't have to wait as long to see an error. This also reduces traffic to your server. Something you probably want to do in a big project is to have some kind of system for writing validation rules centrally, and then using those rules to dynamically generate both PHP and Javascript validation. The advantage of doing that is that you don't duplicate your business rules in two places, but in a smaller project it's probably not worth the hassle.
Validation in the frontend looks about like this: You bind an event handler to an appropriate event or events (you can add onkeydown="validateUserName()" for example, so that the validation reacts a bit quicker), and update your warning text appropriately.
<form action="" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p>
<input id="username" name="username-field" type="text" onblur="validateUserName()" />
<span id="UsernamehelpText"></span>
</li>
</ul>
</form>
<script type="text/javascript">
function validateUserName() {
var userNameElement = document.getElementById('username');
//Do your work: Get the value of the user name field, check
// the values against your validation rules...
var helpText = document.getElementById('UsernamehelpText');
if(isValid)
helpText.innerHTML = "";
else
helpText.innerHTML = "Invalid!";
}
</script>
In the backend, when you process the form, you then have to check the same rules in PHP to prevent illegal values from being posted either maliciously or due to an error in your Javascript. If an error is found, you don't save, instead you can just re-render the form with the submitted values in the input fields and a message indicating what was invalid - this allows the user to change their inputs without losing the values they submitted.
With jQuery it would look something like this:
function someFunction() {
$.ajax({
url: "checkStuff.php",
data: $("input[name='username-field']").serialize,
success: function(data) {
if (data == "correct") {
$("#UsernamehelpText").html("Valid");
} else {
$("#UsernamehelpText").html("Invalid");
}
}
});
}
Your PHP could be something very simple that just checks the validity of the input and then echos "correct" if it is.

Simple Honeypot Form Check with PHP and AJAX

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.

Showing an alert() dialog box if a form does not have valid values

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

How to mimic struts validation using javascript/html/css

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.

Categories