How to prevent a form from submit if text box is empty?
This I have done in JSP successfully using alert message.
Javascript:
function validate()
{
var x=document.forms["Form1"]["comp"].value;
if (x==null || x=="")
{
alert("comp cannot be blank");
return false;
}
<form name="Form" action="welcome.php" onsubmit="return validate()" method="post">
<input type="text" name="comp">
How can I do the same using PHP? So that whenever a user submits without entering text it should give message to user through an javascript alert() message.
I can display alert message:
echo '<script language="javascript">alert("comp cant blank");</script>';
But how can i give condition?what are the changes has to be made in the above please put it in a code form.i have to do it only in PHP.
You cannot stop a form from submitting using PHP.
PHP is server side, you would need to have Javascript to handle the form submit if there is an issue with your validation. You should handle validation on both client side (JS) and server side (PHP).
So no, not possible with just PHP as you outlined, the form WILL submit, then you validate it. Can't stop it with PHP (as its just HTML to the user).
you can used from this jquery code:
$("#btnSubmitID").click(function(event){
if($("#txtID").val()==''){
event.PreventDefault();
alert("your message");
}
});
this is a sample, you can validate your form with this way before post to the server.
You could submit the form using XHR (known as AJAX) and have php verify the data.
You would still need to submit the XHR using javascript.
Your javascript code looks fine and it should not submit the form when its empty. However, if you want to do from PHP code, you can do the same, but the form needs to submit and return back to same page when its not valid (or empty).
Here is sample code
<?php
if ($_POST['comp'] == '')
{
header("location:yourpagename");
}
else
{
// process
}
?>
And now for the non-pseudo code answer. This is working, tested code that elaborates on the concepts I already posted.
<?php
function formWasPosted()
{
return array_key_exists( 'comp', $_POST );
}
// -------
function validate( &$errors )
{
if ( $_POST['comp'] == '' )
{
$errors['comp'] = 'cannot be blank';
}
return count( $errors ) == 0;
}
// -------
function getError( $fieldName, $errors )
{
$out = '';
if ( array_key_exists( $fieldName, $errors ) )
{
$out = '<span class="errorMsg">' . $errors[$fieldName] . '</span>';
}
return $out;
}
//------------------------------------------------------------------------
// $errors will be passed to our validate function so we can set error messages per field if desired.
$errors = array();
$formMsg = '';
if ( formWasPosted() )
{
if ( validate( $errors ) )
{
// do processing here
header( 'Location: http://www.example.com/success' );
exit();
}
$formMsg = '<div class="errorNotice">There were problems with your submission</div>';
}
?>
<html><head>
<script type="text/javascript">
function validate()
{
var x=document.forms["Form1"]["comp"].value;
if (x==null || x=="")
{
alert("comp cannot be blank");
return false;
}
}
</script>
<style>
.errorMsg, .errorNotice { color: red; }
.errorNotice { font-size: 150%;}
</style>
</head>
<body>
<?php echo $formMsg; ?>
<form name="Form" action="welcome.php" onsubmit="return validate()" method="post">
<label for="comp">Comp <?php echo getError( 'comp', $errors ); ?></label>
<input id="comp" type="text" name="comp">
</form>
</body>
</html>
Here is the general approach I use for processing forms.
Pseudo code:
Has Form Been Submitted?
Is form valid?
process form (db insert/update/delete, other operation here
Else
Print form with error messages and optionally a javascript alert
End is form valid
Else
Print form without error messages
End has form been submitted
Related
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 some javascript and php code written to validate a field. Both codes are to validate whether the field is not empty, is within a limit of 35 characters and contains only alphabetic characters and a hyphen(-). What i want to do is for both the javascript and php to validate simultaneously and show they're messages for entering incorrect data but it only seems that the javascript is validating properly due to the fact that an alert pops up but no message is shown from the php side. Here is my code :
<script type="text/javascript">
function validateFamily()
{
var family=document.getElementById('family');
var stringf = document.getElementById('family').value;
var ck_password = /^[A-Za-z-]/;
if (family.value=="")
{
alert("Family name must be filled out");
return false;
}
else if (document.getElementById('family').value.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if(!ck_password.test(stringf))
{
alert("Family name can only contain alphabetic characters and hypehns(-)");
return false;
}
return true;
}
</script>
<?php
if (isset($_POST['submit'])) {
$flagf = false;
$badcharf = "";
$stringf = $_POST["family"];
$stringf = trim($stringf);
$lengthf = strlen($stringf);
$strmsgf = "";
if ($lengthf == 0) {
$strmsgf = '<span class="error"> Please enter family name</span>';
$flagf = true;}
else if ($lengthf > 35) {
$strmsgf = '<span class="error"> Can not enter more than 35 characters</span>';
$flagf = true;}
else {
for ($if=0; $if<$lengthf;$if++){
$cf = strtolower(substr($stringf, $if, 1));
if (strpos("abcdefghijklmnopqrstuvwxyz-", $cf) === false){
$badcharf .=$cf;
$flagf = true;
}
}
if ($flagf) {
$strmsgf = '<span class="error"> The field contained the following invalid characters: '.$badcharf.'</span>';}
}
if (!$flagf) {
$strmsgf = '<span class="error"> Correct!</span>';}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateFamily() && validateGiven() && validateMaleFemale() && validDate() && validateAddress() && validatePost() && validateParent() && validateWork() && validateHome() && validateMob() && validateCheckBoxes() && validateTextBoxes();">
<b>Student's Family Name</b>
<br>
<input type="text" id="family" name="family" /><?php echo $strmsgf; ?>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Could anyone help me with this?
Your JavaScript and PHP cannot execute simultaneously because the former happens in the user's browser before the form is POSTed and the latter happens after this once the form has reached the server.
You can verify this by inspecting the source code of your webpage in the browser: there's no PHP!
If your JavaScript makes the catch, nothing is sent to the server because you return false. In practice it makes sense to have the server-side checks in place in case:
Someone is tricky and modifies the form after it's validated but before it's sent.
JavaScript is disabled or breaks for some reason.
The way this form works is that you have a JS function in the form's onsubmit property which can prevent the form's submission if a value is wrong. If your JS function returns false because of an error, the form will never be submitted.
In order to get the functionality you want, you need to perform the checks on the server side only, but you'll need to submit the form each time for that to occur...
An alternative way would be to check the entered values when the user finishes adding a value to each of your text fields, i.e. attach a JS function to the fields' blur() property, and make an AJAX call to your server that will validate the field contents before the form is actually submitted.
You can use jQuery's validate plugin for more complex validations, if these can be done on the client side, as well:
http://jqueryvalidation.org/
As paislee stated there is no way you can simultaneously run php and javascript. There are however dynamic requests you can send to run some php code and it's called AJAX. This will also not ensure an absolutely accurate simultaneous execution but will be closer to what you aim for.
I'm trying to validate a form using Ajax and onchange function. Basically I want automatic validation once the focus is gone from the input box. Then it will state an error if it's blank / invalid entry.
For some reason the validation works for invalid entries but won't work for empty inputs on first try (meaning if i refresh page and go to second field box by tab, there's no error). The funny thing is the empty error works fine after i erase an entry. I've tried using $var = "" or empty($var) but I still get the same results.
Here's the php part:
if(isset($_GET["isbn"]) )
{
$isbn = $_GET["isbn"];
$error="";
if(empty($isbn) || !preg_match("/^\d{12}$/", $isbn) )
{
$error .= "Please enter a valid ISBN";
echo $error;
}
else
echo $error;
}
Here's the rest:
<script type="text/javascript">
function validateIsbn(keyword)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.status == 200 && xhr.readyState == 4)
{
var res = xhr.responseText;
document.getElementById("err1").innerHTML = res;
}
}
xhr.open("get","validate_isbn.php?isbn=" + keyword,true);
xhr.send();
}
</script>
<form method="get" action="">
<label class="top-label">ISBN:</label>
<input name="isbn" id="isbn" type="text" onchange="validateIsbn(this.value)"/>
<div id="err1"> </div>
<p></p><p></p>
You say you want automatic validation once the focus is gone from the input box. The event triggered in that case is onblur, not onchange.
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'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