How to mimic struts validation using javascript/html/css - php

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.

Related

PHP $_POST is empty after using jquery val() on input

I want to check value of input for year of birth. I have figured out that if I use jquery function val() to get value of this input, so the php post of this input will be empty. It works fine without using val(). Here you can see the important part part of code. It is not so essential ability of form, but it would be useful to check if the isn't written anything inappropriate or any mistype.
Thank you for help.
<?php
if (!empty($_POST['rn']) && isset($_POST['rn'])){
// proceed
} else {
echo "You haven't filled all inputs";
}
?>
<script>
$("#kontrolaButton").click(function(){
var rok = parseInt($("#rok_nar").val(),10);
if (rok > 1900 && rok < 2016) {
$("#odeslatButton").trigger('click');
};
});
</script>
<form accept-charset="utf-8" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="send_form">
<input class="bold" id="rok_nar" type="text" name="rn" placeholder="Rok narození"/>
<input type="button" value="Odeslat" name="kontrola" id="kontrolaButton" />
<input type="submit" value="Odeslat" name="odeslat" id="odeslatButton" style="visibility: hidden;" />
</form>
Update:
I have probably found the problem. I didn't write it here, because I didn't consider it as an issue. My script looks like:
$("#kontrolaButton").click(function(){
var rok = parseInt($("#rok_nar").val(),10);
alert(rok);
if (rok > 1900 && rok < 2016) {
$("#odeslatButton").trigger('click');
};
});
After erasing the alert, the code works :/ Interesting...
It looks like your trying to access an input in the dom before it is loaded. I don't see a document ready. You need to either stick your script inside a document ready so it is delayed until the dom is completely parsed, or move your logic at the bottom of your page so the elements exist by the time you try to look them up.
You should move the script right to the end of the HTML body so that it executes when the kontrolaButton element is in the DOM.
Note that the mouse down/up or key press/release you issue to close the alert(rok); may interfere with the submission of the form. For instance, I could reproduce a problem like this: I pressed the ESC key to close the alert, and although the form submitted its data, the next page did not render; it was just a blank page. This may be very browser dependent, but on my set-up the ESC key apparently interrupts the rendering of a page.
There may be other such side effects, certainly also if you have other Javascript code on the page that responds to these key or mouse events.

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.

PHP Using both client side and server side validation WITHOUT using 3rd party code

EDIT: thanks for all the help. Received an email saying that we didn't need the client side so I scrapped that idea in favor of actually completing the assignment on time.
Before you ask, Yes this is assignment work. No I am not looking for someones complete code. I am a beginner will practically no experience in HTML/PHP/javascript, but this is the second part of the assignment so I already have some of my own code from the first part, which was so very easy in comparison to this part. The task doesn't specifically say we have to use client side validation, but I feel it would be good practice.
I need someone to clearly show me how to use both client and server side validation. I already have the javascript validation, but I can modify it as it displays an alert box for every error. I CANNOT use 3rd party code like jQuery which apparently everyone on the internet likes to use, and the course I am doing doesn't like to actually teach us any useful content so we are all on our own.
The data from the form will then be entered into a database through MySQL (which I am not looking forward to doing), and from viewing the minimal information from w3schools on the topic, I understand that I have to POST the form to itself.
The form itself is pretty simple: contains name, DoB, email, postcode etc.
My current .js uses alpha only, num only, date format, email format, radio button and check box checks and every field is tested to make sure it isn't empty.
I suppose what I am after is a complete tutorial on how to do this. My internet searches have been unfruitful, but at least I still have a week till this is due.
Any help is appreciated, but simple and clear help would be even more so. I will continue to prowl the internet for help until then and post back here if I find useful stuff for anyone else with the same problem (which I'm sure is 90% of my class.....)
Thanks in advance.
Read the code below. Hope inline comments answer your question.
add_record.php
<?php
if(isset($_POST['name'])) {
//get post data
$name = trim($_POST['person_name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
//This is server-side check!
if (strlen($name) > 10){
echo "FAILED! You tried to submit a name which is greater than 10 chars."
}else{
//insert to the database here..
//and send out a "success message or render HTML
echo "SUCCESS!";
}
}else {
echo "Error! Proper parameters were not provided!";
}
a.html
<html>
<head>
<script type="text/javascript">
function checkForm(){
//client side (JS) validation. This happens before submitting.
var name = document.forms[0].person_name.value;
if (name.length > 10){
alert("Name is too long");
return false;
}
//do some more checks here..
//return true if all checks have passed, false otherwise.
//the return value of this function is checked before submit. The form is submitted only when this function returns a true.
return true;
}
</script>
</head>
<body>
<form action="add_record.php" method="POST" onsubmit="return checkForm()">
Name: <input type="text" name="person_name"/>
Email: <input type="text" name="email"/>
Message: <input type="text" name="message"/>
<input type="submit"/>
</form>
</body>
</html>
EDIT: As mplungjan pointed out, it is not a good idea to have a field named "name" inside forms. The form object itself might have a "name" which might conflict.
Since it's homework, I should at least point you to a few resources:
Client side
For validation:
http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html (form validator)
http://www.javascriptkit.com/javatutors/re.shtml (regular expression guide)
Don't jump to AJAX straight away, that's advanced material. Get the basics done first and just let the form submit to PHP (i.e. page refreshes and PHP redraws the form if there were any validation issues).
Server side
For validation: http://www.php.net/filter - examples
For database work: http://www.php.net/pdo - tutorial
For server side validation, you would send the form data to a php page using method="post", then check for correct format. Something like:
<form action="validate.php" method="post">
<!-- form fields -->
</form>
In validate.php, you use $_POST["var_name"], where var_name is the name of your input fields, to check the data. So, for example, something like:
$age = $_POST["age"];
if (ctype_digit($age) && $age > 0) {
// correct format
}
It seems like you already have client side validation figured out. I'm not quite sure if I understood your problem correctly, though - Let me know where specifically you are having problems and I'll try to help.

How to cause a form field to be required

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.

Categories