Implementing a live email checker with a syntax email checker - javascript

I followed an example, http://formvalidation.io/examples/using-data-returned-validator/, and was able to implement simple validation for email and usernames. I found another demo/example which uses ajax to call a live email checker php script.
What I have not figured out is how to implement (combine) the live username checker with the standard validator so that it both checks to see if the email is of a valid format in addition to be available to use, not a registered member already. Messing with the javascript, I have gotten the validator to see my php script, check_email.php using an AJAX post.
However I don't have the right syntax to make the validator make use of the result of the php script to return a message like 'Duplicate" or "Email in use". The html for the email:
<!-- EMAIL -->
<div class="form-group">
<div class="row">
<label class="col-xs-6 control-label">Email address</label>
<div class="col-xs-6" style='clear:left;width: 50%;'>
<input type="text" class="form-control email" name="email" />
</div>
</div>
</div>
The relevant part of the javascript:
<script>
$(document).ready(function() {
$('#taskForm').formValidation({
framework: 'bootstrap',
icon: {
// required: 'fa fa-asterisk',
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
'email': {
validators: {
notEmpty: {
message: 'The email address is required'
},
emailAddress: {
message: 'The input is not a valid email address'
}
,
remote: {
type: 'POST',
url: 'check_email.php',
message: 'Duplicate or whatever ...',
cache: false,
success: function(result){
var result=remove_whitespaces(result);
if(result=='')
{
// Do something ...
}
}
}
}
},
}
})
});
</script>
To see the demo form visit http://dottedi.us/validation/validator.php. To illustrate that the live checker works use the username of 'sowhat' and email address of 'sowhat#dottedi.biz' to test. I have the username working separately with a username checker just to show that it works, not the desired method. Email is currently broken with my code.
I can modify check_email.php if necessary. Currently it returns $HTML='email exists'; if is a duplicate.
The question: how do I change the structure, syntax of the remote function so that it can make use of a response from check_email.php?
Oh, and here is the php code in check_email.php:
<?php
include ("mysql_connection.php");
$HTML = "";
if(isset($_POST['email']) && !empty($_POST['email']))
{
$email=strtolower(mysql_real_escape_string($_POST['email']));
$query="select * from members where LOWER(email)='$email'";
$res=mysql_query($query);
$count=mysql_num_rows($res);
if($count > 0){ $HTML='email exists'; }else{ $HTML=''; }
}
echo $HTML;
?>

I kept digging and found the answer at: http://formvalidation.io/validators/remote/
1) Changed the relevant javascript to:
remote: {
message: 'This email address is taken',
url: 'check_email.php',
type: 'POST'
}
2) Changed check_email.php to return JSON format response:
if ( $count > 0 ) { $status = false; } else { $status = true; }
if(isset($status))
{
$data = array(
"valid" => $status,
"email" => $email // OPTIONAL
);
echo json_encode($data);
}

Related

Sending static data using bootstrapValidator locally

how to use a remote back-end to check if a given username is already taken or not.
check and validate locally without using database or web-server
This is latest version of bootstrapValidator, jquery, html5, bootstrap.
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script>
<form id="registrationForm" class="form-horizontal">
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
</form>
and custom js is
$(document).ready(function() {
$('#registrationForm').bootstrapValidator({
fields: {
username: {
message: 'The username is not valid',
validators: {
remote: {
message: 'The username is not available',
url: 'default.php',
data: {
type: 'username'
}
}
}
}
}
});
});
back-end default.php file is
<?php
$isAvailable = true;
switch ($_POST['type']) {
case 'username':
default:
$username = $_POST['username'];
data = 'admin','root';
$isAvailable = true;
break;
}
echo json_encode(array(
'valid' => $isAvailable,
));
username already exists or not from default.php file, error
not showing.
$(document).ready(function() {
$('#registrationForm').bootstrapValidator({
fields: {
username: {
message: 'The username is not valid',
validators: {
callback: {
callback: function(value, validator) {
var data = "user1";
if (value === data) {
return {
valid: false,
message: 'The name is not available'
}
}
return true;
}
}
}
}
}
});
});
Instead of using php function, I have used call back function for this it's working fine.

Not able to send bootstrap form from view to controller after bootstrap validations

Scenario
I have a bootstrap form built in codeigniter on which bootstrap
validation has been applied. And i wish that after the validation are
fulfilled the user can click on submit button and goes to the action
page(i.e controller).
Issue:
Submit button is not working, due to which the form is not getting
redirected
Goal:
Make the validation work and then redirect the form to the controller so that > value of the form can be saved in database
NOTE
Here is the link of a sample code that i have, the only
difference between the two is that the question that i am asking is in
codeigniter and the link is without codeigniter. However i need the
answer for codeigniter:
Code
<?php
$reg_attributes = array('id'=>'contact_form','class'=>'form-horizontal');
echo form_open('home/registeruser', $reg_attributes); ?>
<div class="form-group">
<?php
$data = array(
'type'=>'text',
'class' => 'form-control',
'name'=>'fullname',
'autocomplete'=>'off',
'placeholder'=>'Full Name',
'id'=>'user_name'
);
?>
<?php echo form_input($data); ?>
</div>
<div class="form-group">
<?php
$data = array(
'type'=>'submit',
'class'=>'btn btn-success btn-block',
'name'=>'submit',
'content'=>'Register',
'value'=>'submit',
);
echo form_button($data);
?>
</div>
<?php echo form_close(); ?>
Script
<script type="text/javascript">
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fullname: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Please supply your full name'
}
}
},}
}) }); });
</script>
There are two things you need to fix
1 .You are using name "submit" for your submit button change it
<?php
$data = array(
'type'=>'submit',
'class'=>'btn btn-success btn-block',
'name'=>'save',
'content'=>'Register',
'value'=>'submit',
);
echo form_button($data);
?>
Remove extra brackets from your javascript code.
So it will look like this
$(document).ready(function () {
$('#contact_form').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fullname: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Please supply your full name'
}
}
},
}
})
}); // remove extra bracket from here

Check email it is already exist in database, using json returning data from database,

I want to check to see if an email already exists in a table or not.
I am using bootstrap formValidator library, with remote method,
but its not making any proper result.
It always shows the same message, whether its wrong or right, dont know whats wrong.
remote.php
<?php
include("dbcontroller");
$dbhandle=new DBcontroller();
header('Content-type: application/json');
include("connect.php");
$sql="select * from members";
$temp=array();
$result=$db_handle->runQuery($sql);
foreach($result as $row)
{
$temp[]=$row['email'];
}
$valid = true;
if (isset($_POST['email'])) {
$email = $_POST['email'][0];
foreach ($temp as $k => $v) {
if ($email == $v) {
$valid = false;
break;
}
}
}
echo json_encode(array(
'valid' => $valid,
));
?>
Form.php
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-8">
<input type="text" placeholder="Email" id="e_mail" class="form-control" name="email[]" autocomplete="off"/>
</div>
</div>
Javascript file
'emaill[]': {
validators: {
notEmpty: {
message: 'The email address is required and can\'t be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
},
remote: {
message: 'The email is already exist. you are already a registered user. please try to login?',
url: 'remote.php',
data:{
type:'email'
},
type: 'POST',
delay: 2000
}
}
}
Why don't you do the check in your SQL query?
$sql = "SELECT email FROM members WHERE email = '".$_POST['email']."'";
Now you only have to check if it returns more than 0 results:
$valid = false;
$result=$db_handle->runQuery($sql);
if(sizeOf($results) > 0) {
$valid = true;
}
Although you probably should escape the $_POST the avoid SQL injection ;-)

jQuery validation plugin multiple remote issue. Is it me or bug?

I am using jQuery Validation plug-in in my two step registration form.
On "First Step" I'm checking username and email availability with remote function.
Here is the bug (or me!):
If username exist in database and email is not, when I click "next" button the script letting me go to second step. (It shouldn't because username exist!)
but;
If username not exist and email is exist in the database, It's stops me there and warns me email is exist. So it's working.
If both username and email exist in the database, also stops me. So again working.
Here is code I'm using;
HTML:
<div class="tab-content">
<p>Page.</p>
<form class="form-horizontal" onsubmit="return false;" action="" method="post" id="myform">
<div id="stepusername">
<p>This is step 1</p>
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="email" class="form-control" id="email" name="email" placeholder="email" autocomplete="off"><br>
<p><a class="btn btn-primary next">Go to step 2</a></p>
</div><!-- signup_one ends -->
<div id="stepemail">
<p>This is step 2</p>
<input type="password" class="form-control" id="password" name="password" placeholder="password" autocomplete="off"><br>
<input type="password" class="form-control" id="conf_password" name="conf_password" placeholder="password" autocomplete="off"><br>
<input class="btn btn-success next" type="submit" value="Finish">
</div><!-- step2 ends -->
</form>
<div id="stepsuccess">
<p>Show result here.</p>
</div><!-- success ends -->
</div><!-- tab-content ends -->
Java Script:
<script type="text/javascript">
// jQuery.validate script, does client-side validation
$(document).ready(function(){
$(".next").click(function(){
var form = $("#myform");
form.validate({
errorElement: 'div',
errorClass: 'formerror',
highlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').addClass("has-error");
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass("has-error");
},
rules: {
username: {
required: true,
remote: {
url: "check-username.php",
async: false,
type: "post", }
},
password : {
required: true,
},
conf_password : {
required: true,
equalTo: '#password',
},
email: {
required: true,
remote: {
url: "check-email.php",
async: false,
type: "post", }
},
},
messages: {
username: {
required: "Username required",
remote: "Taken username.",
},
password : {
required: "Password required",
},
conf_password : {
required: "Password required",
equalTo: "Password don't match",
},
email: {
required: "Email required",
remote: "Taken email.",
},
}
});
if (form.valid() === true){
if ($('#stepusername').is(":visible")){
current_fs = $('#stepusername');
next_fs = $('#stepemail');
}else if($('#stepemail').is(":visible")){
current_fs = $('#stepemail');
next_fs = $('#stepsuccess');
}
next_fs.show();
current_fs.hide();
}
});
});
</script>
Update:
check-username.php
<?php
error_reporting(E_ERROR | E_PARSE);
try {
$handler = new PDO('mysql:host=localhost;dbname=users', 'root', '');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$request = $_REQUEST['username'];
$query = $handler->query("SELECT * from usertable WHERE username='$request'");
$results = $query->fetch(PDO::FETCH_ASSOC);
if(empty($request)) {
echo 'false' ;
}else {
if ($results == 0) {
$valid = 'true';
}
else {
$valid = 'false';
}
echo $valid ;
}
?>
check-email.php
<?php
error_reporting(E_ERROR | E_PARSE);
try {
$handler = new PDO('mysql:host=localhost;dbname=users', 'root', '');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$request = $_REQUEST['email'];
$query = $handler->query("SELECT * from usertable WHERE email='$request'");
$results = $query->fetch(PDO::FETCH_ASSOC);
if(empty($request)) {
echo 'false' ;
}else {
if ($results == 0) {
$valid = 'true';
}
else {
$valid = 'false';
}
echo $valid ;
}
?>
Also jsFiddle if you like to see: http://jsfiddle.net/noptpece/
$query = $handler->query("SELECT * from usertable WHERE username='$request'");
This line doesnt look, if a user exists, whos name equals the content of $request, it looks up if the user with the name "$request" exists, the same with the e-mail.
String composing in PHP works differently, you should write
$query = $handler->query("SELECT * from usertable WHERE username=".$request);
Also you should never ever use a MySQL query like this, because its the easiest thing of the world to inject SQL code and destroy your whole database.

Validate form fields using ajax

I do have a jquery code to validate my form but unfornutately it is not that accurate. I would like to validate the fields thoroughly like only to accept numbers on phone field and only a valid email address on email field.
Also I would like to show the error ( or just add a red border one field ) as soon as the user types/inputs a value without clicking submit button, so it looks like a real time checker.
Can anyone derive my script, I am really not confident about this. Also derive my php code if u think it is wrong. Would love to learn how to use session also so user can only submit once every session.
Code:
<head>
<script>
$(function () {
$('.cbf').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
if ( name == "" ) {
alert('Please provide valid name');
$('#name').addClass('error');
}
else if ( phone == "" ) {
alert('Please provide a valid phone number');
$('#phone').addClass('error');
$('#name').removeClass('error');
}
else if ( email == "" ) {
alert('Please provide a valid email');
$('#email').addClass('error');
$('#phone').removeClass('error');
}
else {
$.ajax({
type: 'post',
url: 'index.php',
data: $('.cbf').serialize(),
data: "name="+ name +"& phone="+ phone +"& email="+ email,
success: function () {
alert('We will contact you shortly! Thanks!');
},
complete:function(){
$('.cbf').each(function(){
this.reset(); //Here form fields will be cleared.
});
}
});
$('#email').removeClass('error');
}
});
});
</script>
</head>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" class="cbf">
<fieldset>
<input type="text" id="name" name="name" value="" placeholder="Name">
<input type="text" id="phone" name="phone" value="" placeholder="Phone">
<input type="email" id="email" name="email" value="" placeholder="Email Address">
<input type="submit" id="submit" name="submit" value="Get Call Back">
</fieldset>
</form>
<?php
session_start();
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$_SESSION['posted'] = true;
$to = "myemail#gmail.com";
$subject = "Someone wants a Call Back!";
// data the visitor provided
//$name_field = $_POST['name'];
//$phone_field = $_POST['phone'];
//$email_field = $_POST['email'];
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_INT);
//constructing the message
$body = " From: $name_field\n\n Phone: $phone_field\n\n E-mail: $email_field\n\n";
// ...and away we go!
mail($to, $subject, $body);
} else {
// handle the error somehow
}
?>
Try this code :
$("#signupform").validate({
rules: {
email: {
required: true,
email: true
},
mobile: {
required: true,
number: true,
minlength: 10,
maxlength: 10
}
},
messages: {
email: {
required: "Please enter a valid email address.",
email: "Invalid Email Address."
},
mobile: {
required: "Please provide a mobile number.",
minlength: "Your mobile number must be 10 characters long.",
maxlength: "Your mobile number must be 10 characters long.",
number: "Please Enter number only."
}
}
});
Its better to validate on both server side and client side. Client side validate then display the error to user. On server side, you need to validate again, just because your JS code can be changed by malicious user.
A simple example with phone.
//client side
var phone = $('#phone').val();
//validate
if(/^\d+$/.test(phone) === false){ //not number
alert('Your phone number is not valid');
}
//on server side
$phone = $_POST['phone'];
if(is_numeric($phone)){
insert $phone into database.
}
Another way is to use HTML5 and new tags like : "email" and "tel" (tel is not supported for the moment) :
<input type="tel" name="phone" required>
and for email :
<input type="email" name="email" required>
Even the solution you choose, you have to do a control on the server side in Php for your case.
It's not the solution but in the futur, I think we should use these tags.
More informations : http://www.w3schools.com/html/html5_form_input_types.asp
Here is a simple jQuery validation:
The form:
<form id="myform">
email<input type="text" name="field1" />
<br/>
password<input type="text" name="field2" />
<br/>
<input type="submit" />
</form>
The validation part
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
http://jsfiddle.net/VuPPy/

Categories