I'm using Ajax to test if the Username on a Register form is too short.
Right now it just does this:
if (str.length<6)
{
document.getElementById("txtHint").innerHTML="Too short";
return;
}
How do I add an action above that doesn't let the user submit?
<form action="/insert/insert-user.php" method="post">
<input type="text" name="user" onkeyup="showHint(this.value)"/>
In the CheckUserName function, add your ajax code and return true or false. If It's false, it won't submit.
<form action="/insert/insert-user.php" onsubmit="CheckUserName()" method="post">
You may try adding a form name and onsubmit event to your form.
<form name="formName"action="/insert/insert-user.php" method="post" onsubmit="validate()">
function validate() {
if (document.formName.user.value.length < 7) {
// Display your message in your division
return false;
}
}
You must also repeat the check in php since the user may have Javascript disabled and for security measure:
if ($_POST['your_submit_button']) {
if (strlen($_POST['user']) < 7) {
$submit = false;
die ("<div style='color: red;'>Too short</div>");
}
}
Give your error div a class lets say 'error' and on submitting the form call another function in which you check the if error class have text by JQuery. If the class have the text just return false and your form will not be submitted
Related
I'm working on a form that I'd like to change the form action based off of the value of an input on form submit. This needs to be accomplished using PHP.
Here's what I've tried so far:
<?php
$action = "";
$input = (isset($_POST["hp"]));
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
<!-- form stuff here -->
<input id="hp" name="hp" type="text" class="hp"/>
<input type="submit" name="submit" id="submit" value="Submit Query" class="button" />
</form>
This doesn't work because the hp field for (isset($_POST["hp"])) doesn't have a value from the get-go, so it always goes to action1.
I've also tried:
<?php
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
$action = "";
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
That didn't work because Perch (the CMS this is being built on) throws you an error that $action isn't defined yet.
And when I tried:
<?php
$action = "";
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
It didn't do anything at all on submit because it set the action as "".
Any suggestions?
To write in short way
$action = isset($_POST['hp'])?'action2':'action1';
That's all.
Differents possibilities:
Same action and redirect
The most easy way probably is send form to the same PHP file, and in this file, get the content of this input via POST and redirect to the correct file.
Prevent default submit and add submit event via JavaScript
The second option, may be add an event to form on submit via JavaScript, prevent default action to prevent the submit, then check value of input, set action and submit form:
<form name="contactForm" id="contactForm" method="post" action="">
...
</form>
<script>
document.querySelector('#contactForm').addEventListener('submit', function(e) {
//Prevent default submit
e.preventDefault();
//Check input value
if (...) {
this.action = "page1.php";
} else if (...) {
this.action = "page1.php";
}
//perform submit form.
this.submit();
});
</script>
Use data binding library
This is probably the best form to do it, but the most complicated to understad, this form is based of use a data binding library like Vue.js, KnockoutJS or RactiveJS to set in model object the action string depending of input value.
Then, in HTML form tag, set in action the value of model data using the binding syntax of the chosen library:
//Vue.js syntax
<form name="contactForm" id="contactForm" method="post" :action="action">
//Ractive.js syntax
<form name="contactForm" id="contactForm" method="post" action="{{action}}">
What do I recommend?
If you're novel with PHP and don't know JavaScript, the first option is probably the best for you, if you If you know JavaScript and you know how to work with events, but never used a binding library, probably the second option is more recommended for you.
If you worked with some data binding library (or framework that implements data binding like Angular), the third options is probably the best for you.
If the 2nd and 3rd versions don't work, you must be missing an input like:
<input type="submit" name="submit">
You can either add that button to the form, or you can change your code to use if isset($_POST['hp'])
<?php
$action = "";
if(isset($_POST['hp'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
None of the answers above worked for me, so here is what I ended up going with.
Use Case:
I have a "Search" form with two fields. When a user clicks "Search",
these values should be added to the URL, so that previous searches
may be bookmarked. The search should then be performed.
When the page is first loaded or no search criteria are used, all
possible results should be shown.
Code description:
At the top of the file, check if the user submitted the form.
If so:
get the values from the fields you want and save them to local variables.
navigate to the same PHP file, this time passing the variables you are interested in
If the user did not submit the form:
check for URL parameters
If there are URL parameters present, save them to local variables,
and use these local variables to run the search
Code Snippet:
if(isset($_POST['submit'])){
if(!empty($_POST['projectNameSearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_POST['projectNameSearch']);
}
if(!empty($_POST['projectDescriptionSearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_POST['projectDescriptionSearch']);
}
if($projectNameSearch != '' || $projectDescriptionSearch != ''){
header("Location: projects.php?projectnamesearch=$projectNameSearch&projectdescriptionsearch=$projectDescriptionSearch");
}
} else {
if(isset($_GET['projectnamesearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_GET['projectnamesearch']);
}
if(isset($_GET['projectdescriptionsearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_GET['projectdescriptionsearch']);
}
}
I have a form and I validate the fields in javascript functions. After the validation, I want to redirect to another page. I am trying this for the form:
<form action="" method="post" name="form" onsubmit="return validate()">
User Name : <input type="text" name="realname" size="19"><span id="realnameerror" ></span>
<br>
E-Mail : <input type="text" name="email" size="25"><span id="emailerror" ></span>
<br>
PhoneNo : <input type="phoneno" name="phoneno" maxlength="10" size="25"><span id="phonenoerror" ></span>
<br>
<input type="submit" value="Submit">
</form>
And this is the code for validation:
<script type="text/javascript">
var hasFocus = false;
function checkName(form) /* for name validation */
{...}
function checkEmail(form) /* for email validation */
{...}
function validPhone(form) /* for phone validation */
{...}
function validate()
{
hasFocus = false;
var form = document.forms['form'];
var ary=[checkName,checkEmail,validPhone];
var rtn=true;
var z0=0;
for (var z0=0;z0<ary.length;z0++)
{
if (!ary[z0](form))
{
rtn=false;
}
}
if (rtn)
{
window.location="http://test.dev";
return rtn;
}
else return rtn;
}
</script>
The point is that all the javascript functions are working correctly, I get error messages if there are any, but it just doesn't make my redirect. The weird thing is that if I put the redirect into another script, and don't make the validation, it works. I don't know what am I doing wrong. I have tried to put my redirect into another function and just call it like this:
if (rtn) { Redirect(); }
but it still doesn't work. Instead of window.location I also tried window.location.href and document.location.href. I really think there something that I'm missing inside the script... If you notice something, please let me figure it out. Thank you!
I HAVE TRIED TO PUT AN ALERT INSIDE MY IF STATEMENT AND IT APPEARS FOR 2 SECONDS AND THEN IT MAKES THE REDIRECT. IF I DON'T PUT THAT ALERT, MY REDIRECT DOESN'T WORK. HERE IS THE CODE:
if (rtn) {
window.location="http://test.dev";
alert(rtn);
}
if (rtn)
{
alert('hello there');
window.location="http://new/new.php";
return true;
}else{
return false;
}
when true condition first then page redirect to given url and for condition second not redirect.
alert something inside this code
if (rtn)
{
alert('you here');
window.location="http://test.dev";
return rtn;
}
if alert come out, you got here. If not, your first condition is wrong. That we split out where to have problem.
if (rtn)
{
window.location="http://test.dev";
return rtn;
}
else return rtn;
Replace the above with
return rtn;
The form does not submit if we return false and submits otherwise.
Also, the form will submit to "action", so make sure your "action" property of form is set to "http://test.dev"
Set form tag's action to be http://test.dev.That's all.
Edit: You never think about the form data may not be posted to http://test.dev if you used window.location.href?
How doing this?
<form action="http://test.dev" method="post" name="form" onsubmit="return validate()">
<script type="text/javascript">
var hasFocus = false;
function checkName(form) /* for name validation */
{...}
function checkEmail(form) /* for email validation */
{...}
function validPhone(form) /* for phone validation */
{...}
function validate()
{
hasFocus = false;
var form = document.forms['form'];
var ary=[checkName,checkEmail,validPhone];
var rtn=true;
var z0=0;
for (var z0=0;z0<ary.length;z0++)
{
if (!ary[z0](form))
{
rtn=false;
}
}
if (rtn)
{
return rtn;
}
else return rtn;
}
</script>
Try jquery ajax to redirect true statement
$.ajax({url: 'search.php',data: "check_qc=" + qc,async:false,
success: function(response) {if(response==1){window.location="http://google.com";
return false;}}});
I have been working on creating a form with a set of fields like username, passwords etc....
I want to make validation when the SUBMIT button is clicked.
I'm trying to get alert from my border color. All fields are valid my border must change into Green color If it has any errors it should change to red color.
Any one has any ideas regarding to my problem
If anyone has any suggestion??
You can use jquery plugin.... here you are. JQuery Form validation custom example
Use jQuery validation plugin: http://docs.jquery.com/Plugins/Validation
In this plugin, you have to define validation rules for the field. You can also set the error messages for given field for given validation rule.
This plugin adds classes to valid and invalid field.
You have to give the css for that class.
For example:
$(document).ready(function(){
$(".my_form").validate({
rules:{ // validation rules
email_address: {
required:true,
email: true
},
password:{
minlength: 6
},
confirm_password: {
equalTo:"#password"
}
},
messages: {
email_address: {
required: "Please enter email address",
email: "Please enter valid email address",
},
/*
likewise you can define messages for different field
for different rule.
*/
}
errorClass: "signup_error",
/*This is error class that will be applied to
invalid element. Use this class to style border.
You can give any class name.*/
});
});
Once you click on submit button, and field is invalid, the plugin adds class to the element that you have specified as errorClass, and when you enter valid value in the field, the plugin will remove this class and will add 'valid' class by default.
You can use these two classes to style valid and invalid element using simple element.
.valid {
border-color:"green"
}
.signup_error {
border-color:"red"
}
Hope this resolves your problem.
Js i the way to go. You can find some really good validators for jQuery should you google for it.
To custom build a simple validator I would go like this
<form class="validator">
<input type="text" name="my-input-1" data-validator="integer"/>
<input type="text" name="my-input-2" data-validator="email"/>
....
</form>
<script>
$("form.validator").submit(evt, function() {
var errors = 0;
$(this).find('[data-validator]').each(function(e, i) {
var value = $(this).value;
switch($(this).data('validator')) {
case 'integer':
if (!(parseFloat(value) == parseInt(value)) && !isNaN(value)) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
case 'email':
if (..... // regex validate email ...) {
$(this).css({'border-color': '#FF0000'});
errors++;
} else
$(this).css({'border-color': '#000000'});
break;
}
});
if (errors > 0) {
// If you want to prevent default event execution no matter what
evt.preventDefault();
// If you want you other attached events to NOT run
evt.stopPropagation();
// signal failure
return false;
}
// All is well, go on
return true;
});
</script>
of course it's always good practice to build functions for every validator and even better to wrap the whole thing in a jQuery widget (I would suggest using jQuery Widget Factory) which would allow you to enhance it in the future and keep you flexible to changes
You can use DOJO library to validate form fields. It's easy to implement.
Given below is the tutorial to implement dojo
http://dojotoolkit.org/documentation/tutorials/1.6/validation/
and this is the working example you can see...
http://dojotoolkit.org/documentation/tutorials/1.6/validation/demo/dijitcheck.html
I made a validation library just for general javascript purposes. It is even unit tested! You can override whatever you want fairly easily as well: https://github.com/parris/iz
As far as highlighting invalid fields you can just change the style of that field or add a class. The example below just changes the background color of the input and adds a message.
Working example: http://jsfiddle.net/soparrissays/4BrNu/1/
$(function() {
var message = $("#message"),
field = $("#field");
$("#the-form").submit(function(event) {
if (iz(field.val()).alphaNumeric().not().email().valid){
message.text("Yay! AlphaNumeric and not an email address");
field.attr("style","background:green;");
} else {
message.text("OH no :(, it must be alphanumeric and not an email address");
field.attr("style","background:red;");
}
return false;
});
});
The validator is called iz. It simply lets you chain validations together and it will tell you if everything passed or if you check the "errors" object it'll give you more specifics. Beyond that you can specify your own error messages. Check the docs on github.
What is happening here is we are setting a click handler for the submit event once the page is ready. return false; at the bottom of the submit callback prevents the form from submitting. If you return true; the form will continue on. Instead of return false you could also event.preventDefault(); but I prefer the return syntax for consistency. In the real world with multiple form elements you may do something like this (psuedo code):
var passed = true;
if (check field 1 is false)
...
if (check field 2 is false)
...
if (check field n is false)
passed = false
style and add message
if passed
return true
else
return false
The if statement checks the validation rules and makes changes to the DOM accordingly. By doing it in this way you are able to give a complete list of all passed and failed fields with a full description of what is incorrect.
I have used this plugin in the past, makes implementation very easy and has good documentation and examples.
My advice use jQuery
to try first create multiple inputs and give them a class
html:
<input type="text" class="validate" value="asdf" />
<input type="text" class="validate" value="1234" />
<input type="text" class="validate" value="asd123" />
<input type="text" class="validate" value="£#$&" />
<input type="text" class="validate" value=" " />
then use the code below to see how it works
jQuery:
// Validate Function
function validate(element) {
var obj = $(element);
if (obj.val().trim() != "") {
// Not empty
if (!/^[a-zA-Z0-9_ ]{1,10}$/.test(obj.val())) {
// Invalid
obj.css('border-color', '#FAC3C3');
if (!obj.next().hasClass('error'))
{ obj.after('<span class="error">Please use letters or numbers only and not more than 10 characters!</span>'); }
else
{ obj.next().text('Please use letters or numbers only and not more than 10 characters!'); }
} else {
// Valid
obj.css('border-color', 'lightgreen');
if (obj.next().hasClass('error'))
{ obj.next().remove(); }
}
} else {
// Empty
obj.css('border-color', '#FAC3C3');
if (obj.next().hasClass('error'))
{ obj.next().text('This field cannot be empty!'); }
else
{ obj.after('<span class="error error-keyup-1">This field cannot be empty!</span>'); }
}
}
$(document).ready(function() {
// Each
$('.validate').each(function() {
// Validate
validate(this);
// Key up
$(this).keyup(function() {
// Validate
validate(this);
});
});
});
jsfiddle : http://jsfiddle.net/BerkerYuceer/nh2Ja/
A server side validation example of your need. You may try it out.
<?php
error_reporting(0);
$green = "border: 3px solid green";
$red="border: 3px solid red";
$nothing="";
$color = array ("text1"=>$nothing , "text2"=>$nothing) ;
if ( $_POST['submit'] ) {
if($_POST['text1']) {
$color['text1'] = $green;
}
else $color['text1'] = $red;
if($_POST['text2'] ) {
$color['text2'] = $green;
}
else $color['text2'] = $red;
}
?>
<form method="post">
<input type="text" name="text1" style="<?php echo $color ['text1']?>" value="<?php echo $_POST['text1']?>">
<input type="text" name="text2" style="<?php echo $color ['text2']?>" value="<?php echo $_POST['text2']?>">
<input type="submit" name="submit">
</form>
Note
Always sanitize user input.
error_reporting off is not a good practice at all. I did it as this is not a code of production environment.
Check before trying to access in the post array using isset or something similar function like this.
Always check if a variable exist before using.
$("#btn").click(function(){
// Check all of them
if( $.trim($("#file").val()) == ""){
$("#file").css("border","1px solid #ff5555");
}else{
$("#file").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimBaslik").val()) == ""){
$("#showboxResimBaslik").css("border","1px solid #ff5555");
}else{
$("#showboxResimBaslik").css("border","1px solid #cccccc");
if( $.trim($("#showboxResimEtiket").val()) == ""){
$("#showboxResimEtiket").css("border","1px solid #ff5555");
}else{
if($.trim($("#showboxResimSehir").val()) == ""){
$("#showboxResimSehir").css("border","1px solid #ff5555");
}else{
$("#showboxResimSehir").css("border","1px solid #cccccc");
$("#resimYukleForm").removeAttr("onSubmit");
$('#resimYukleForm').bind('submit', form_submit);
}
}
}
}
});
probably the easiest way is to use this javascript:
http://livevalidation.com/examples#exampleComposite
I think it suits your description the best.
check below link, here i have only checked for empty fields and if the fields are empty then changed input fields id which will change input field border color.
http://jsfiddle.net/techprasad/jBG7L/2/
I have used
$("#myb").click(function(){
that is on button click event but you can use submit event.
Here is what I would say is short precise and concise way to do this in jQuery.
HTML:
<form id="myform" name="form" action="http://www.google.com">
<div class="line"><label>Your Username</label><input class="req" type="text" /></div>
<div class="line"><label>Your Password</label><input class="req" type="password" /></div>
<div class="line"><label>Your Website</label><input class="req" type="text" /></div>
<div class="line"><label>Your Message</label><textarea class="req"></textarea></div>
<div class="line"><input type="submit" id="sub"></submit>
</form>
CSS:
.line{padding-top:10px;}
.inline input{padding-left: 20px;}
label{float:left;width:120px;}
jQuery:
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid green");
$(".req").each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0) {
$(this).css("border","1px solid red");
valid = false;
}
});
return valid;
}
$("#sub").click(function() {
$('#myform').submit(validateform);
$('#myform').submit();
});
});
LIVE DEMO
Well hi, you can use html5 "required" and "pattern" in your form's fields.
You'll get red border if it's wrong and green if it's right.
You can even style the :valid and :invalid entry fields if the colors aren't which you wanted.
I've never tested it but why not, it's better than nothing ;)
html5 solution
Firs Learn javascript, if you have some basic knowledge of js and need to know the logic, go on read..
First you need an event handler to run a function on form submit
Easiest way is (though there are better ways)
<form action="som.php" onsubmit="functionName()">
form here
</form>
This will trigger the function called functionname.
In function name function access the input fields and validate using regular expressions
function functionName()
{
//verification code
if(verified)
{
//code to change border to green
}
}
You need to get the input fields and validate them. If you don't know how to do that, get a few Javascript books
If you need to validate as soon as value is typed use the on onchange event on input fields
I have:
form.php
preview.php
form.php has a form in it with many dynamically created form objects. I use jquery.validation plugin to validate the form before submitting.
submit handler:
submitHandler: function() {
var formData = $("#myForm").serialize();
$.post("preview.php", {data: formData },function() {
window.location.href = 'preview.php';
});
Question:
- How to change the current page to preview.php and show the data? my submitHandler doesnt work? Any tips?
preview.php:
$results = $_POST['data'];
$perfs = explode("&", $results);
foreach($perfs as $perf) {
$perf_key_values = explode("=", $perf);
$key = urldecode($perf_key_values[0]);
$values = urldecode($perf_key_values[1]);
}
echo $key, $values;
enter code here
You can simply add the onsubmit even of the form and use your validation check along a function. At the end if anything is going good, return it with a true state otherwise, false to stop it from getting submitted.
For example:
<form name="Iran" method="POST" action="preview.php" onsubmit="return alex90()">
</form>
And use this script:
<script language="javascript">
function alex90()
{
// use whatever validation you want
if(form == valid){
return true;
}else{
alert("Something's wrong folk!");
return false;
}
}
</script>
Just submit the form without ajax and make sure action of form is "preview.php"
EDIT: to do this in validation plugin simply remove the submitHandler option you show above. This is used if you want to over ride normal browser form submit, which you now don't want to do.
WIth your ajax submit, then trying to go to the page.... it is 2 page requests and without the form redirecting automatically there is no data available on page load using the javascript redirect
I managed to solve my problem. without sessions.
add to form:
<form action="preview.php" onsubmit="return submitForPreview()">
<input type="hidden" name="serial" id="serial" value="test">
js:
function submitForPreview()
{
if($("#form").valid()){
$('#serial').val($("#newAdForm").serialize());
return true;
}else{
return false;
}
}
preview.php
echo $_POST['serial'];
//Which shows the serialized string. YEEEEYYY :D
Thanks for help folk :D
I want to check the value enter in the form by user. i have applied validation and its working. The problem is that if user enter any form value incorrectly and then clicks submit, the whole page is refreshed and all input data is lost.
I want that validations is checked before passing it to server. One of my friends told me its possible with AJAX. Can anyone guide a beginner on how to do this?
You can use javascript instead and save the server from transferring some extra KBs and calculations by using Ajax (which technically is javascript but you send the request back to the server)
Jquery has a plugin called validation that will make your life easier though:
http://docs.jquery.com/Plugins/validation
There is a live demo in the link above
For example if you wanted to validate the username you could do this
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
</script>
<form id="commentForm">
<input id="uname" name="name" class="required" />
</form>
yes you can use ajax or otherwise with your current approach you can use sessions to store user data and prevent it from being lost. with ajax you can show response from the server to show to the user.
$.ajax({
url: 'ajax_login.php',
type:'post'.
data:(/*data from form, like,*/ id: $('#username').val())
success: function( data ) {
if(data == 1) {
$('.feedback').html('data has been saved successfully');
//redirect to another page
}
else {
$('.feedback').html('data could not be saved');
$('.errors').html(data);
}
}
});
ajax_login.php would be something like
<?php
if(isset($_POST)) {
//do form validation if it is valid
if(form is valid) {
saveData();
echo 1;
}
else {
echo $errors;
}
}
?>
Do not need ajax.
Just set the onsubmit attribute of your form to "return checkfun();" and define checkfun some way like this:
function checkfun()
{
if ( all things were checked and no problem to submit)
return true;
else
{
alert('ERROR!');
return false;
}
}