having issues to validate form using JavaScript - php

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;

Related

Ajax PHP + MySQL registration form tutorial

Until now I have
HTML
<form id="account_reg" action="reg.php" method="post">
<div id="response"></div>
<div class="input">
<label>Login</>
<input name="login" type="text" class="required" id="login" size="30"/>
</div>
<div class="input">
<label>Password</>
<input name="password" type="text" class="required" id="password" size="30"/>
</div>
<div class="input">
<label>Repeat Password</>
<input name="rpassword" type="text" class="required" id="rpassword" size="30"/>
</div>
<div class="input">
<label>Email</>
<input name="email" type="text" class="required" id="email" size="30"/>
</div>
<div class="button">
<input type="submit" name="send" id="send" value="Send"/>
</div>
<div class="input">
<input type="hidden" name="honeypot" id="honeypot" value="http://"/>
<input type="hidden" name="humancheck" id="humancheck" class="clear" value=""/>
</div>
</form>
MY PHP
I have some validation on server side.
`
include("dop/config.php"); //includ Db connect
$login = ($_POST['login']);
$password = ($_POST['password']);
$rpassword = ($_POST['rpassword']);
$email = ($_POST['email']);
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];
if ($honeypot == 'http://' && empty($humancheck)) {
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-Za-Z.](2,4)$/";
if(!preg_match($reg_exp, $email)){
$error_message .="<p>A Valid email is required</p>";
}
if(empty($login)){
$error_message .="<p>enter login</p>";
}
if(empty($password)){
$error_message .="<p>Enter password</p>";
}
if(empty($rpassword)){
$error_message .="<p>Enter password again</p>";
}
if($password != $rpassword){
$error_message .="<p>password mut match</p>";
}
}
else {
$return['error'] = true;
$return['msg'] = "<h3>There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}
My JS
With Validation.
$('#send').click(function(e)
{
e.preventDefault();
var valid = '';
var required =' is required.';
var login = $('#account_reg #login').val();
var password = $('#account_reg #password').val();
var rpassword = $('#account_reg #rpassword').val();
var email = $('#account_reg #email').val();
var honeypot = $('#account_reg #honeypot').val();
var humancheck = $('#account_reg #humancheck').val();
if(login = ''){
valid ='<p> Your Name '+ required +'</p>';
}
if(password='' || company.length<=6){
valid +='<p> Password '+ required +'</p>';
}
if(rpassword != password){
valid +='<p> password must match </p>';
}
if(!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i))
{
valid +='<p> Your Email' + required +'</p>';
}
if (honeypot != 'http://') {
valid += '<p>Spambots are not allowed.</p>';
}
if (humancheck != '') {
valid += '<p>A human user' + required + '</p>';
}
if(valid !=''){
$('#account_reg #response').removeClass().addClass("error")
.html('<strong> Please Correct the errors Below </strong>' + valid).fadeIn('fast');
}
else{
//$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('#account_reg').serialize();
$('#send').val("Please wait...");
submitForm(formData);
}
});
function submitForm(formData) {
$.post('reg2.php',formData, function(data){
//console.log(data);
$('#send').val("Send");
if (data === '1') {
alert('ok!');
} else {
alert('wrong shit');
}
});
};
I didn't do yet the MySQL part With Inserting and checking if account is already registered.
The first problem that I have is on Click event redirects me on reg.php even when I use e.preventDefault();
If anybody knows a good tutorial for creating registration form or any suggestion.
The form is submitted, that is why you get to reg.php. From what I see you are submitting the data with a custom function anyway so the quickest way to fix that would be to change the submit input into a regular button. So
<input type="submit" name="send" id="send" value="Send"/>
becomes
<input type="button" name="send" id="send" value="Send"/>
I think that it might also help if you return false when you find an error in the function that validates the form when.
A side question: I find it strange that you chose to have a honeypot field with a value (http://). Usually those fields are empty.. Is there any specific reason for doing so?
You need to keep all your JS code expect function submitForm(formData) inside $(document).ready(function(){});
If I'm not wrong there is no variable with name company so change this variable to password i,e. in second if condition of your validation.
Note: If some errors exist in your code then don't escape from those errors instead try to debug it.
there is something wrong with JS code when the code is not working
maybe you can try from this example for SignupForm using JQuery http://bit.ly/1aAXy5U

Validating a textbox

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.

Checking if a PHP array is empty in JavaScript

Hi I have a form where a user can enter one or more books into a DB. Whenever a user enters one book and forgets to enter the title, a JavaScript alert comes and alerts him to enter a title. Now if he has two or more books and he forgets to enter the title, the alert doesn't show up.
This is my JavaScript function.
function validateForm()
{
var a=document.forms["submit_books"]["title"].value;
if (a==null || a=="")
{
alert("Please enter a Title");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.submit_books.email.value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
}
And Here is my PHP code
<form method="post" name="submit_books" onsubmit="return validateForm()" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php for ($i=1; $i<$num_of_books + 1; $i++){
echo "<strong>Book # $i</strong><br><br>";
?>
<label for="title">*Title</label>: <input type="text" id="title" size="60" name="title[]" autocomplete="off"/><br><br>
<?php }?>
<input type="submit" name="submit" value="Submit Books">
</form>
I even tried putting the PHP array into a JavaScript one.
<?
$js_array = json_encode($title);
echo "var title = ". $js_array . ";\n";
?>
var index = 1;
if( index < title.length)
{
alert("Please enter a Title");
return false;
}
There must be an easier way doing this
You should be doing
var index = 1;
if( index > title.length )
{
alert("Please enter a Title");
return false;
}
Since there is no record if title.length = 0, that is, if 1 > 0 then there is no title.
You can also check
if( title.length === 0 )
Try to use inside html form
<label>
<span>Book Title: (required)</span>
<input name="book" type="text" placeholder="Please enter your books title" required autofocus>
</label>
Then use javascript to validate
(function() {
// Create input element for testing
var inputs = document.createElement('input');
// Create the supports object
var supports = {};
supports.autofocus = 'autofocus' in inputs;
supports.required = 'required' in inputs;
supports.placeholder = 'placeholder' in inputs;
// Fallback for autofocus attribute
if(!supports.autofocus) {
}
// Fallback for required attribute
if(!supports.required) {
}
// Fallback for placeholder attribute
if(!supports.placeholder) {
}
// Change text inside send button on submit
var send = document.getElementById('submit');
if(send) {
send.onclick = function () {
this.innerHTML = '...Processing';
}
}
})();
You can do this like:
<?
echo "var title_length = ". count($title) . ";\n";
?>
var index = 1;
if( index > title_length)
{
alert("Please enter a Title");
return false;
}

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
});
});

Categories