It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a username form. Which have 2 fields, username and password.
Basically I want it so if the user has not entered the fields and pressed 'submit' an error displays like
"Please enter the required fields"
I know it's possible with JavaScript or PHP but unsure how to do it.
Here is the code of the user and password form:
<div id="sessionContainer" class="clearfix">
<div class="content">
<form action="goto.php" class=" sign-in" method="post">
<div style="margin:0;padding:0"></div>
<h3>Enter Details</h3>
<p><font size="-1">Please enter your details</font></p><br>
<div class="clearfix">
<label for="">Username or email address</label><br>
<input class="xlarge" id="email" name="email" tabindex="1" type="text" value="" />
</div>
<div class="clearfix">
<label for=""><br>
Password</label><br>
<input class="xlarge" id="password" name="password" tabindex="2" type="password" value="" />
</div>
<p class="remember"> </p>
<p class="remember">
<button class="btn btn-m btn-blue" id="signin_submit" name="commit" type="submit" tabindex=5>Sign in</button>
</p>
Thanks
<?php if(!isset($_POST['email']) || !isset($_POST['password'])
This code will check if either of those fields has a value. If it does not, you can output an error message. The code in the whole context is as follows:
<?php if(!isset($_POST['email']) || !isset($_POST['password']): ?>
<div>Please fill in all fields!</div>
<?php endif; ?>
This is my answer...in clasic javascript xD:
<html>
<head>
<script type="text/javascript">
function validar()
{
var right = 1;
if(document.getElementById('email').value.length==0)
{
right = 0;
document.getElementById('emptymail').innerHTML = "Empty Mail o Username";
}
if(document.getElementById('password').value.length==0)
{
right = 0;
document.getElementById('emptypass').innerHTML = "Empty Password";
}
if(right == 1)
{
document.forms["formu"].submit();
}
}
</script>
</head>
<body>
<form action="goto.php" class=" sign-in" method="post" name="formu" id="formu">
<div style="margin:0;padding:0"></div>
<h3>Enter Details</h3>
<p><font size="-1">Please enter your details</font></p><br>
<div class="clearfix">
<label for="">Username or email address</label><br>
<input class="xlarge" id="email" name="email" tabindex="1" type="text" value="" /><div id="emptymail"></div>
</div>
<div class="clearfix">
<label for=""><br>
Password</label><br>
<input class="xlarge" id="password" name="password" tabindex="2" type="password" value="" /><div id="emptypass"></div>
</div>
<p class="remember"> </p>
<p class="remember">
<button class="btn btn-m btn-blue" id="signin_submit" name="commit" type="button" tabindex=5 onclick="validar();">Sign in</button>
</p>
</form>
</body>
</html>
Saludos ;)
HTML only solution using the required attribute (works only in newer browsers):
<input required="required" />
An example how to do a jscript based solution can be found here, here or this one with a little jquery help.
Use jQuery Validate for validations
Download it from here and call it. and then add this code
rules:
{
email:
{
required: true
}
},
messages:
{
email:
{
required: "Please enter your email."
}
}
OR simply Use HTML 5 validations
<input id="email" name="email" type="text" value="" required />
To do it using JavaScript, you are looking for the OnSubmit attribute of your form
There are numerous things you can do if the function you called with OnSubmit fails (returns false), but as an example this code will show a popup box
<script>
function checkForm()
{
if (document.getElementById('email').value.length==0 || document.getElementById('password').value.length==0)
(
alert("fill in required fields")
return false;
)
return true;
}
<script>
Then in your form tag you put
<form onsubmit="return checkForm()" ...
var $form = $('form'),
$user = $('#email),
$pass = $('#password');
$form.on('submit', function(e) {
e.preventDefault(); // stop the default behavior
if ($user.text().length === 0) {
$user.addClass('error'); // do something with the error class or add attribute 'required'
} else if ($pass.text().length === 0) {
// do something else
} else if ($user.text().length > 0 && $pass.text().length > 0) {
// post the form
$.ajax({
url: //URL where you send,
data: $form.serialize(),
success: function(e) { // do something },
error: function(e) { // do something }
});
}
}
Related
I'm not sure what to do here..
The PHP post request (request.php) just continues to next page after clicking the button (correct.html) even if I don't type anything in the input.
I'd want it to verify that the password is correct, if so = continue to correct.html, else alert user.
PHP code:
<?php
$pass = $_POST['password'];
if ($pass == "password")
{
include "correct.html";
}
else
{
echo "Password incorrect";
}
?>
HTML code:
<div class="input-container">
<input class="input-field" type="password" placeholder="Your passphrase" /><br>
<i class="fa fa-user icon"></i>
</div><br>
<div id=continue>
<form action="request.php" method="post">
<button class="button" name="password" value="password" style="vertical-align:middle"><span>Confirm</span></button>
</form>
</div>
You should first add name attribute value for input type password or
button like below
<div id=continue>
<form action="request.php" method="post">
<input class="input-field" type="password" name="password" placeholder="Your passphrase" />
<button class="button" name="submit" value="submit" style="vertical-align:middle"><span>Confirm</span></button>
</form>
</div>
After your php code should be like this
<?php
if(isset($_POST['submit']))
{
$pass = $_POST['password'];
if ($pass == "password")
{
include "correct.html";
}
else
{
echo "Password incorrect";
}
}
?>
You should read about Form submissions in PHP. In this particular instance your form isnt submitted as button need submit attribute, i.e. <button type="submit".
Also, to debug the post data, you can use var_dump($_POST); die();.
Here's what your form must be:
<div id=continue>
<form action="request.php" method="post">
<!-- Note that input and button are under the SAME <form> -->
<input class="input-field" type="password" name="password" placeholder="Your passphrase" />
<!-- Note `name` attributes of `button` and `input` -->
<button class="button" name="button" value="submit" style="vertical-align:middle"><span>Confirm</span></button>
</form>
</div>
On server:
<?php
// for debugging purposes, remove when you want
print_r($_POST);
// as 'password' is now NAME of INPUT, `$pass` stores the value from the INPUT
$pass = $_POST['password'];
if ($pass == "password")
{
include "correct.html";
}
else
{
echo "Password incorrect";
}
I'm validating a form using the JQuery validation plugin.
The very first time the page loads, the form is validated perfectly and only submits once all fields have been completed. The form then posts back to itself and when trying to enter details again, the validation does not work but still allows to submit and the data gets successfully sent to the database.
Here is my code:
<form id="formSubmit" method="post" action="post to this page">
<fieldset data-role="fieldcontain">
<p>
<label for="clubSelect">Preferred Club</label>
<select id="clubSelect" name="clubSelect" class="required">
<option value="000">Select a Club</option>
<?php if ($db->num_rows > 0)
{
foreach($results as $result)
{
?>
<option value="<?php echo $result->id;?>"><?php echo $result->name;?></option>
<?php
}
}
?>
</select>
</fieldset>
<fieldset data-role="fieldcontain">
<label for="txtName">Name</label>
<input type="text" id="txtName" name="txtName" class="required"/>
</fieldset>
<fieldset data-role="fieldcontain">
<label for="txtEmail">Email</label>
<input type="text" id="txtEmail" name="txtEmail" class="required email" minlength="5"/>
</fieldset>
<fieldset data-role="fieldcontain">
<label for="txtCell">Contact Number</label>
<input type="tel" id="txtCell" name="txtCell" class="required"/>
</fieldset>
<fieldset data-role="fieldcontain">
<input type="submit" name="submit" value="Submit"/>
</fieldset>
</form>
<script>
$(document).ready(function () {
$("#formSubmit").validate({
rules: {
clubSelect: {
selectcheck: true
},
txtName: {
required: true
},
txtEmail: {
required: true
},
txtCell: {
required: true,
number: true
}
},
messages: {
txtName: {
required: "Please enter your name."
},
txtEmail: {
required: "Please enter your email address."
},
txtCell: {
required: "Please enter your contact number.",
number: "Only numbers are allowed."
}
}
});
jQuery.validator.addMethod('selectcheck', function (value) {
return (value != '000');
}, "Please select a club.");
});
</script>
Basically what I am asking is how to make sure that the validation always works.
Thanks
Replace
$(document).ready(function ()
with
$('#pagID').on('pageshow', function () {
Update: Also, add data-ajax=false to the form div, to avoid posting data using Ajax.
jQuery Mobile Events
Why not to use .ready
I am working on a form that will be validated in Javascript and then, if it is valid, proceed to a PHP submission. The PHP is working fine and will not allow a submission if the input isn't valid. However, I can't get the form to stop before going to the PHP page if the validation function returns as false. Does anyone know what I can do to make this work?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Form</title>
<script src="contact.js" type="text/javascript"> </script>
</head>
<body>
<form name="contact"id="contact" action="contact.php" onsubmit="return formSub();"method="post" >
<h2 class="headingText"><em>What's your name?</em></h2>
<p>
<label for="firstName">First Name </label>
<input type="text" name="firstName" id="firstName" tabindex="7">
<span id="firstNameHTML" class="error"> </span>
</p>
<p>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" tabindex="8">
<span id="lastNameHTML" class="error"> </span>
</p>
<p> </p>
<h2 class="headingText"><em>What's your preferred email address?</em></h2>
<p>
<label for="email">Email Address</label>
<input type="text" name="email" id="email" tabindex="9">
<span id="emailHTML" class="error"> </span>
</p>
<p> </p>
<h2 class="headingText"><em>What would you like to contact us about?</em><br><span id="interestHTML"></span>
</h2>
<p>
<label>
<input type="checkbox" name="Interest" value="training" id="Interest_training" tabindex="10">
Training Services</label>
<br>
<label>
<input type="checkbox" name="Interest" value="testing" id="Interest_testing" tabindex="11">
Testing Services</label>
<br>
<label>
<input type="checkbox" name="Interest" value="remediation" id="Interest_remediation" tabindex="12">
Remediation Services</label>
<br>
<label>
<input type="checkbox" name="Interest" value="General Question" id="Interest_general" tabindex="13">
General Question</label>
<br>
<label>
<input type="checkbox" name="Interest" value="error" id="Interest_error" tabindex="14">
Report a Website Error</label>
<br>
<label>
<input type="checkbox" name="Interest" value="other" id="Interest_other" tabindex="15">
Other</label>
</p>
<p>
<label for="comment"><span class="headingText">Please enter your question or comments here. </span></label><br>
<span id="commentHTML"></span>
<textarea name="comment" id="comment" cols="45" rows="5" width="100px" tabindex="16"></textarea>
</p>
<input name="submit" type="submit" value="Submit the Form" tabindex="17">
<input name="reset" type="reset" value="Reset the Form" tabindex="18">
</form>
<p> </p>
<p> </p>
</body></html>
Javascript Document:
// JavaScript Document
function checkForm()
{
formReset();
var error=0;
//Check firstName has value
if (document.getElementById("firstName").value=="")
{
document.getElementById("firstNameHTML").innerHTML="<strong> Please provide a first name</strong>";
error++;
if(error==1)
{
document.getElementById("firstName").focus();
}
}
//Check lastName has value
if (document.getElementById("lastName").value=="")
{
document.getElementById("lastNameHTML").innerHTML="<strong> Please provide a last name</strong>";
error++;
if(error==1)
{
document.getElementById("lastName").focus();
}
}
//Check email is valid
if (document.getElementById("email").value=="" || document.getElementById("email").value.search("#") < 0)
{
document.getElementById("emailHTML").innerHTML="<strong> Please provide a valid email address</strong>";
error++;
if(error==1)
{
document.getElementById("email").focus();
}
}
//Check Interest has value
if (document.getElementByName("Interest").value=="")
{
document.getElementById("InterestHTML").innterHTML="<strong> Please let us know what you are interested in contacting us about.</strong>";
error++;
}
//Check Comment has value
if (document.getElementById("comment").value=="")
{
error++;
document.getElementById("commentHTML").innerHTML="<strong> Please provide your questions or comments here</strong><br>";
if(error==1)
{
document.getElementById("comment").focus();
}
}
if (error==0)
{
alert("Passed");
return true;
}
alert("Failed");
return false;
}
function formReset(){
document.getElementById("firstNameHTML").innerHTML="";
document.getElementById("lastNameHTML").innerHTML="";
document.getElementById("emailHTML").innerHTML="";
alert("Reset");
}
function formSub(){
if(checkForm())
{
alert("Check is True");
document.getElementById("contact").submit();
return true;
}
alert("I'm sorry, your submission cannot be completed.");
return false;
}
You should do:
onsubmit="return formSub();"
delete javascript:
If your function returns false the form wont be submitted.
You have made a mistake on checkForm function. getElementsByName returns an array of elements. So, in order to check if all of them are unchecked, you have to replace the code with this:
//Check Interest has value
var interests = document.getElementsByName("Interest");
var noneChecked = true;
for(var i = 0; i < interests.length; i++) {
if (interests[i].checked) {
noneChecked = false;
}
}
if (noneChecked) {
document.getElementById("interestHTML").innterHTML="<strong> Please let us know what you are interested in contacting us about.</strong>";
error++;
}
Then your function will work as you wanted.
Hi i am getting error while putting validations for email in PHP5.2
see my below code: i have called checkemail() and written function checkemail() in script. but i am getting error like Error: Duplicate entry '' for key 'PRIMARY' as i have declare email id as primary key. when i put anything in email id then it accepting in database. i think function is not executing properly. guide if have suitable solutions.if required any details then let me know.
<head>
<script>
function checkEmail()
{
$strEmail= mysql_real_escape_string($_POST['email']);
if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $strEmail))
{
return true;
}
else
{
return false;
}
}
</script>
</head>
<body>
<div class="container">
<section id="content">
<form name="form1" method="post" action="check_register.php">
<div>
<input type="text" placeholder="Enter username" required="" id="uname" name="uname"/>
</div>
<div>
<input type="text" placeholder="Enter Email-id" required="" id="email" name="email" onfocus="checkEmail('email');" />
</div>
<div>
<input type="password" placeholder="Enter Password" required="" id="pass" name="pass"/>
</div>
<div>
<input type="password" placeholder="Repeat Password" required="" id="rpass" name="rpass" onfocus="checkPassword(document.getElementById('pass'), this);" oninput="checkPassword(document.getElementById('pass'), this);"/>
</div>
<div>
<input type="text" placeholder="Enter country" required="" id="country" name="country"/>
</div>
<div>
<input type="submit" value="Register" />
</div>
</form>
</section>
</div>
<script src="form-validation.js"/></script>
</body>
Do you check if the mail already exists in the database before trying to insert it ? I think you problem is here. No matters html5 or validation of the email.
And by the way, please never use <script> balise to execute php code. Use <?php /* your code here */ ?> instead.
You can also use a built-in PHP function to validate your email using filter_var, check the first example: http://www.php.net/manual/en/filter.examples.validation.php
yeah why dont use filter_var,
filter_var ($isEmail, FILTER_VALIDATE_EMAIL);
And eregi (Posix Regex) has been deprecated as PHP 5.3.0. php-manual
I have a very simple question but its been bugging me for quite some time .I have a html contact us page in which I have a simple form which already has validation assigned to it.The form code is :
<div class="contact_form">
<form method="post" id="contactForm" name="contactForm" action="">
<fieldset class="contactFieldset">
<ul>
<li>
<label for="contactName" class="leftLabel">*Name:</label>
<input type="text" name="contactName" id="contactName" class="contactInput required" value="" />
</li>
<p></p>
<li>
<label for="email" class="leftLabel">*Email:</label>
<input type="text" id="email" name="email" class="contactInput email required" value="" />
</li>
<span class="simple-success">I'll be in touch soon</span>
<li>
<label for="subject" class="leftLabel">*Subject:</label>
<input type="text" name="subject" id="subject" class="contactInput required" value="" />
</li>
<p></p>
<li>
<label for="message" class="leftLabel">*Message:</label>
<textarea rows="10" cols="40" id="message" name="message" class="contactTextarea required"></textarea>
</li>
<p></p>
<li>
<input type="submit" alt="Submit button" name="submit" class="submit" id="submit">
</li>
</ul>
</fieldset>
</form>
</div>
The code which I am using to try and call the php form using ajax is this
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
alert("test i am here");
/*get the email value*/
var email = $("input#email").val();
var name = $("input#contactName").val();
var subject = $("input#subject").val();
var message=$("input#message").val();
alert("email"+email);
/* Check if the email is good or bad */
var goodEmail = email.match(/\b(^(\S+#).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
apos=email.indexOf("#");dotpos = email.lastIndexOf(".");lastpos=email.length-1;
var badEmail = (apos<1 || dotpos-apos<2 || lastpos-dotpos<2);
/*If the email is bad ,display the error message*/
if (email=="" || !goodEmail || badEmail) {
$("email").focus();
return false;
}
var dataString = 'email='+ email + '\n Name='+ name+ '\n Subject='+ subject+ '\n message='+ message;
alert (dataString);
$.ajax({
type: "POST",
url: "mai.php",
data: dataString,
//Do not cache the page
cache: false,
success: function(html) {
$('.simple-sucess').fadeIn(100).show();
$('.contact_form').fadeOut(100).hide();
$('.simple_error').fadeOut(100).hide();
}
});
return false;
});
});
The thing is the alert is not even being displayed when I press the submit button..what am I doing wrong here?
The validation code is
<script type="text/javascript">
jQuery(document).ready(function($){
$("#contactForm").validate();
});
First of all, use the submit event, not the submit button click event because the submit button is already wired up to do a normal submit. There may also be a bug, be sure to check your javascript console for errors. Either way...
What you probably really want to do is use the jQuery form plugin which will make your code a lot more simple.
Then your revised code would be as simple as:
$('#contactForm').ajaxForm(function() {
$('.simple-sucess').fadeIn(100).show();
$('.contact_form').fadeOut(100).hide();
$('.simple_error').fadeOut(100).hide()
});
In this case you would lose your email validation, but why reinvent the wheel, there are tons of validators out there that already have the bugs worked out etc.
the first thing is you are using :
<input type="submit" alt="Submit button" name="submit" class="submit" id="submit">
in your form, and in jquery you are using .click() event,
if try to change
<input type="submit" alt="Submit button" name="submit" class="submit" id="submit">
to :
<input type="button" alt="Submit button" name="submit" class="submit" id="submit">
then it will work perfectly with the .click() event
or the second option you have if you don't want to change the input type then use .submit() instead of .click()
OMG, so many code lines. A little suggestion: keep it simple enough to debug. A jsfiddle demo is recommended for better answers.
Here I post my solution for ajax forms, which works in basic browsers without javascript support.
html:
<form method="post" id="contactForm" action="somewhere">
Name: <input type="text" name="contactName" />
<br />
<input type="submit" value="Submit this form" />
</form>
javascript:
jQuery(function($){
$('#contactForm').submit(function(e){
e.preventDefault?e.preventDefault():false;
$.post(this.action,$(this).serialize(),function(text){
//callbacks
console.log(text);
});
return false;
})
});