Validating a textbox - php

I am having a table inside a form. I want all the three columns details to be entered by the user. if the user leaves anyone of them, it should show an alert message like "Please enter the name, it cannot be blank". if all the fields are filled then only the insert into should come into act.
<table> <!--cellpadding=15 cellspacing=3-->
<tr><td>Name</td><td>: <input type="text" name="name"></td></tr>
<tr><td>Address</td><td>: <input type="text" name="address"></td></tr>
<tr><td>Phone No</td><td>: <input type="text" name="dept_id"></td></tr>
</table>

Try to use a flag variable.
<input type="text" name="name" id="nameId">
<input type="text" name="address" id="addressId">
<input type="text" name="dept_id" id="dept_id">
Call this method in onSubmit()
function validate()
{
var validate = false;
if(document.getElementById("nameId").value == "")
{
alert("NAME IS REQUIRED");
validate = true;
}
...................
...................
return validate ;
}

$name = trim($_POST['name']);
if (empty($name))
echo 'name is empty';
do this for rest of the fields

<form method="get" enctype="text/plain"action="">
<table> <!--cellpadding=15 cellspacing=3-->
<? if($_GET['name'] == "") print "Please enter the name, it cannot be blank"; ?>
<tr><td>Name</td><td>: <input type="text" name="name"></td></tr>
<? if($_GET['address'] == "") print "Please enter the Address, it cannot be blank"; ?>
<tr><td>Address</td><td>: <input type="text" name="address"></td></tr>
<? if($_GET['dept_id'] == "") print "Please enter the Phone No, it cannot be blank"; ?>
<tr><td>Phone No</td><td>: <input type="text" name="dept_id"></td></tr>
</table>
</form>
and don't forget to properly escape user input!!!

You can use javascript validation on form submit. Look at it below example.
myForm is form name , onSubmit call function validateForm()
function validateForm()
{
if (document.myForm.name.value == "")
{
alert("Please enter the name");
document.myForm.name.focus();
return false;
}
if (document.myForm.address.value == "")
{
alert("Please enter the address");
document.myForm.address.focus();
return false;
}
if (document.myForm.dept_id.value == "")
{
alert("Please enter the department id");
document.myForm.dept_id.focus();
return false;
}
return true;
}

your complete code
<script type="text/javascript">
function validateForm()
{
if (document.test.name.value == "")
{
alert("Please enter the name");
document.test.name.focus();
return false;
}
if (document.test.address.value == "")
{
alert("Please enter the address");
document.test.address.focus();
return false;
}
if (document.test.dept_id.value == "")
{
alert("Please enter the department id");
document.test.dept_id.focus();
return false;
}
return true;
}
</script>
<form method="post" name="test" onsubmit="return validateForm();">
<table> <!--cellpadding=15 cellspacing=3-->
<tr><td>Name</td><td>: <input type="text" name="name"></td></tr>
<tr><td>Address</td><td>: <input type="text" name="address"></td></tr>
<tr><td>Phone No</td><td>: <input type="text" name="dept_id"></td></tr>
<tr><td colspan="2"><input type="submit" name="submit_form" /></td></tr>
</table>
</form>

$(function() {
$("#registration_form").validate({
rules: {
name: {
required: true,
lettersonly:true
},
contact: {
required: true,
numbers:true,
minlength:10,
maxlength:11
}
}
messages: {
name: {
required: "<h4><span style='color:red'>Please Enter your Name</span></h4>",
lettersonly: "<h4><span style='color:red'>Numbers And Symbols Not Allowed</span></h4>"
},
contact: {
required: "<h4><span style='color:red'>Please Enter your Phone number</span></h4>",
numbers: "<h4><span style='color:red'>Character And Symbols Are Not Allowed</span></h4>",
minlength: "<h4><span style='color:red'>Your phone Number Must Be At Least 10 Characters Long</span></h4>",
maxlength: "<h4><span style='color:red'>Please Enter No More Than 11 Numbers</span></h4>"
}
}
submitHandler: function(form) {
form.submit();
}
}); });
jQuery.validator.addMethod("numbers", function(value, element) {
return this.optional(element) || /^[0-9]+$/i.test(value);
}, "numbers only please");
the name is the id of Name field and contact is the id of Phone number Field.

You can use HTML for this kind of validation.
<input type="text" name="name" required>
When the user fails to fill this field , while submitting it will show a pop up message saying Please fill out this field.

Related

don't submit form if form is empty

this is my first post and i'm rather new to php + ajax.
I have most of my coding set up only problem now is that when i press the submit button an notification shows up that only should show up when the text fields aren't empty.
This is my code:
<head><script>
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
alert("Thank you for subscribing to SHCA");
document.forms["ContactForm"].reset();
});
});
</script> </head>
followed by some php coding:
<?php
if(strlen($_POST['name']) > 0 AND strlen($_POST['email']) > 0)
{
if(isset($_POST['submit']))
{
$hostdb = '';
$namedb = '';
$userdb = '';
$passdb = '';
$conn = mysqli_connect($hostdb , $userdb, $passdb ,$namedb);
$sql = "INSERT INTO subscribers (name, email) VALUES('$_POST[name]', '$_POST[email]')";
if (!mysqli_query($conn, $sql))
{
die('Error: ' .mysql_error($conn));
}
if (!mysqli_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysqli_close($conn);
}}
else
{
?>
<form id="ContactForm" action="" method="post">
<label for="author">Name:</label> <input type="text" id="name" name="name" class="required input_field float_r" />
</br>
</br>
<label for="email">Email:</label> <input type="text" id="email" name="email" class="validate-email required input_field float_r" />
<div class="cleaner h10"></div>
<input type="submit" value="Subscribe" id="submit" name="submit" class="submit_btn float_l" />
</form>
<?php } ?>
hope anyone here is able to tell me what i should do to only show the "Thank you for subscribing to SHCA" message when the textfields aren't empty
final anwser Dereck forgot the '' in the objects so shout out to dereck for helping me!
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$('#name').val()) {
alert("please enter your name");
}
if(!$('#email').val()) {
alert("plese enter your email adress");
}
else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});
You need to check the contents of the fields before submitting to the server, a simple script method can check before you submit. If the fields are empty then display an error messge and don't submit the form.
function SubmitDetails()
{
if(window.ContactForm.name.value == "")
{
window.alert("Please enter a name");
return;
}if(window.ContactForm.email.value == "")
{
window.alert("Please enter an email" );
return;
}
window.ContactForm.submit();
}
This should do it without having to do a refresh
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$(#name).val() || !$(#email).val()) {
//don't display
}else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});

javascript validation not activating possibly due to php mailer on HTML form

I have a problem with my Javascript validation not activating. I also have a PHP mailer on this HTML form and as soon as submit is pressed it submits the form and no validation is done.
Here is the code for the HTML form:
<form name="contact" action="mailer.php" onsubmit="return ValidateForm()" method="post"><fieldset>
<tr><td><label for="name">Name:</label></td>
<td><input type="text" name="name" id="name" placeholder="Enter your full name" />
</td></tr>
<tr><td><label for="email">Email:</label></td>
<td><input type="email" name="email" id="email" placeholder="Enter your email address" />
</td></tr>
<tr><td><label for="tel">Phone:</label></td>
<td><input type="tel" name="tel" id="tel" placeholder="Enter your phone number" />
</td></tr>
<tr><td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" placeholder=""></textarea>
</td></tr>
<tr><td><input type="submit" value="Submit" name="submit" />
</form>
Here is the code for the PHP mailer:
<?php
if(isset($_POST['submit'])) {
$to = "email#address.com.au";
$subject = "Subject";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$tel_field = $_POST ['tel'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Phone: $tel_field\n Message:\n $message";
mail($to, $subject, $body, "From: $email_field");
echo "Data has been submitted to $to!";
echo "<a href='index.html'>Go back to Home Page</a>";
} else {
echo "error";
}
?>
Here is the code for the validator:
<script type="text/javascript">
{function validateForm()
{
var x=document.forms["contact"]["name"].value;
if (x==null || x=="")
{
alert("Name field must be filled out");
return false;
}
var x=document.forms["contact"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var x=document.forms["contact"]["tel"].value;
if (y==null || y=="")
{
alert("Phone number must be provided");
return false;
}
var x=document.forms["contact"]["message"].value;
if (x==null || x=="")
{
alert("You have not entered a message");
return false;
}
</script>
I have tried putting the javascript validator in as a separate file on the server or the script itself in the form html document and neither way seems to work. I have done a lot of searching and have checked the code and am pretty sure it's right however could not find anything to say whether or not these two functions are possible together. If someone could please confirm that it would be awesome!
Any advice would be appreciated!
Thanks in advance!
Kaz
In your onSubmit you are calling return ValidateForm() when you should be doing return validateForm() with a lowercase "v". There are some others:
{function validateForm() should be function validateForm()
You never close the functions opening brace after the if statement.
<form name="contact" action="mailer.php" onsubmit="return validateForm()" method="post">
and then:
function validateForm() {
var x = document.forms["contact"]["name"].value;
if (x == null || x == "") {
alert("Name field must be filled out");
return false;
}
var x = document.forms["contact"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
var x = document.forms["contact"]["tel"].value;
if (y == null || y == "") {
alert("Phone number must be provided");
return false;
}
var x = document.forms["contact"]["message"].value;
if (x == null || x == "") {
alert("You have not entered a message");
return false;
}
}

How to add AJAX Submit to PHP validation and return message?

I've been working my way up on validating a form and got the JS and PHP validation to work but I am still having a hard time adding ajax(with or without JQUERY) to submit to the php file and return a success message.
My form with CSS and JS validation:
<html>
<head>
<style type="text/css">
#nameerror {
color:red;
}
#emailerror{
color:red;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
function Validate() {
var email = document.forms['form']['email'].value;
var atpos = email.indexOf('#');
var dotpos = email.lastIndexOf('.');
var name = document.forms['form']['name'].value;
if (name == null || name == ""){
document.getElementById('nameerror').innerHTML="Please enter your name";
return false;
} else if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
document.getElementById('emailerror').innerHTML="Please enter a valid email";
return false;
} else {
}
}
</script>
</head>
<body>
<div>Sign Up</div>
<form name="form" action="form_validation.php" id="form" onsubmit="return Validate();" method = 'post'>
<label>Name:</label><br/>
<input id='name' type="text" name='name' /><br/>
<span id="nameerror"></span><br/>
<label>Email:</label><br/>
<input type='text' name='email' id = 'email'/> <br/>
<span id= "emailerror"></span><br/>
<label>Comments:</label><br/>
<textarea name='comments' id ='comments'></textarea><br/>
<span id="comerror"></span>
<input type="submit" name="submit" value="Submit"/>
<span id="success" style="display:none">Your message has been sent successfully.</span>
</form>
</body>
</html>
And this is form_validation.php:
<?php
if(isset($_POST['submit'])){
if($_POST['name']){
$name = $_POST['name'];
}
if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
echo "Name can only contain letters.";
return false;
} else {
echo "Name accepted";
}
if($_POST['email']){
$email = $_POST['email'];
}
$pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if(!preg_match($pattern, $email)){
echo "Please enter a valid email address.";
return false;
} else {
echo "Email Valid";
}
if($_POST['comments']){
$comments = $_POST['comments'];
}
if (strlen($comments) > 100){
echo "please enter less than 100 characters.";
return false;
}
}
?>
thanks for the help!
$('form').on('submit',function() {
$.ajax({
url: 'form_validation.php',
data: $(this).serialize(),
type: 'POST'
}).done(function(data){
// you can append a success message to your document here
});
});

validate update form

I am creating a page in which I am fetching data from table and showing data in textbox to allow user to update record. I also validate the user input to textbox. But the problem is when the user does not change any field and click on submit, it validates username field i.e. it always wants to change (or edit textbox) the value of textboxes.
Here is my code:
<?php
include("conn.php");
$id=$_GET['id'];
$sql="SELECT * FROM test WHERE id='$id'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
?>
<script type='text/javascript'>
function formValidator()
{
// Make quick references to our fields
alert("hiiiiiii");
var name = document.getElementById('name').value;
var email = document.getElementById('emailid').value;
var ph = document.getElementById('ph').value;
if( name=="" || name==null)
{
alert("Please Enter user name");
return false;
}
var alphaExp = /^[a-zA-Z]+$/;
if(!name.match(alphaExp))
{
alert("please Enter only Alphabates for Name");
return false;
}
if(email=="" || email=="null")
{
alert("Please Enter Email Address");
return false;
}
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(!email.match(emailExp))
{
alert("please Enter valide email address");
return false;
}
if(ph=="" || ph=="null")
{
alert("Please Enter Phone Number");
return false;
}
var numericExpression = /^[0-9]+$/;
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
}
</script>
<form name="updateform" method="POST" action="update_ind_new.php" onsubmit='return formValidator()'>
<table width="200" border="0">
<tr>
<td>User Name</td>
<td>E-Mail</td>
<td>phno</td>
</tr>
<tr>
<td><label>
<input name="name" type="text" id="name" value=" <?php echo $row['name']; ?>" >
</label></td>
<td><label>
<input name="email" type="text" id="emailid" value=" <?php echo $row['emailid']; ?>" >
</label></td>
<td><label>
<input name="ph" type="text" id="ph" value=" <?php echo $row['phno']; ?>" >
</label></td>
</tr>
<tr>
<td> <input name="id" type="hidden" id="id" value=" <?php echo $row['id']; ?>"></td>
<td><label>
<input type="submit" name="Submit" value="Submit">
</label></td>
<td> </td>
</tr>
</table>
</form>
write return true; at the end of this line
if(!ph.match(numericExpression))
{
alert("Enter only Digit for Phone Number");
return false;
}
return true;
Put return true; at the end of all the conditions in the validation function
or put a validations in "if else if else" conditions

having issues to validate form using JavaScript

On this form when I enter the email address correctly and leaves the name field as a blank, the page is submitting and the javacript not running. Otherwise its working fine.
Please someone help me to solve this JavaScript.
function validateform(data)
{
var validField = "";
var namevalid=/^[a-zA-Z ]+$/;
if(data.name.value == ""){validField += "- Please Enter Your Name\n";}
else if(data.name.value.search(namevalid)==-1){validField += "- Entered Name contains Numbers or Symbols\n";}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;
}
<form name="data" onsubmit="return validateform(this);" action="some.php" method="post">
<div>
<label>Name:</label><input type="text" id="name" name="name" size="20" maxlength="20"/></div>
<div>
<label>E- mail Address:</label><input type="text" id="email" name="email" size="20" maxlength="30"/></div>
<input type="submit" name="submit" value="Start Now!"/>
</form>
You need little change in your code. Problem is because function validateform() always returning false irrespective of email validation. Test below working page along with your code. You should add alert and return false in else {} block.
<html>
<head>
<script type="text/javascript">
function validateform(data)
{
var validField = "";
var namevalid=/^[a-zA-Z ]+$/;
if(data.name.value == ""){validField += "- Please Enter Your Name\n";}
else if(data.name.value.search(namevalid)==-1){validField += "- Entered Name contains Numbers or Symbols\n";}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
else {
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;
}
}
</script>
</head>
<body>
<form name="data" onsubmit="return validateform(this);" action="some.php" method="post">
<div>
<label>Name:</label><input type="text" id="name" name="name" size="20" maxlength="20"/></div>
<div>
<label>E- mail Address:</label><input type="text" id="email" name="email" size="20" maxlength="30"/></div>
<input type="submit" name="submit" value="Start Now!"/>
</form>
</body>
</html>
You need to refactor your code a little bit. At the minute if the email address is valid your return true out of the function regardless of the name field.
function validateform(data) {
var validField = "";
var isValid = false;
var namevalid = /^[a-zA-Z ]+$/;
if (data.name.value == "") {
validField += "- Please Enter Your Name\n";
}
else if (data.name.value.search(namevalid) == -1) {
validField += "- Entered Name contains Numbers or Symbols\n";
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value))) {
validField += "- Please Enter A Valid E-mail Address\n";
};
if (validField == "") {
isValid = true;
}
if (!isValid) {
alert(validField);
}
return isValid;
}
You need to place your function between <script> tags, other than that this looks ok to me.
I'm not quite sure why this is failing, but the function isn't called at all. Might be the onsubmit.
Why don't you use a library like jQuery?
Have a look at this example, this works fine: http://jsfiddle.net/tR3XQ/1/
$("form[name=data]").submit(function(){
var validField = "";
var namevalid=/^[a-zA-Z ]+$/;
if(data.name.value == ""){validField += "- Please Enter Your Name\n";}
else if(data.name.value.search(namevalid)==-1){validField += "- Entered Name contains Numbers or Symbols\n";}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;
});​
You need to add a check for a value in validField for the email check otherwise it is ignored
if (validField.length = 0 && /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(data.email.value)){
return true;
}
validField += "- Please Enter A Valid E-mail Address\n";
alert(validField);
return false;

Categories