jquery- How to validate a signature input? - javascript

I have a form that requires user to enter their digital signature before signing up. It looks like below:
So prior to signing up, user MUST enter their signature on the canvas box provided. I use jquery validation to validate my other fields before coming to this final page for signature.
I can validate all the fields except for the signature field. Any idea what I can do?
<div class="row">
<div class="col-12 col-md-8 offset-md-2 pl-3 pr-3 pt-2 mb-0">
<canvas class="display-block signature-pad" style="touch-action: none;"></canvas>
<p id="signatureError" name="signatureError" style="color: red; display: none;">Please provide your signature.</p>
<div class="p-1 text-right">
<button id="resetSignature" class="btn btn-sm" style="background-color: lightblue;">Reset</button>
<button id="saveSignature" class="btn btn-sm" style="background-color: #fbcc34;">Save</button>
</div>
<input type="hidden" name="signature" id="signatureInput">
</div>
</div>
<div class="row">
<div class="col-12 mb-0 pt-2">
<div class="text-right">
<input type="hidden" name="registrationFor" value="customer">
<button type="submit" id="submit" class=" btn next-button bjsh-btn-gradient text-right">Sign Up</button>
</div>
</div>
</div>
var canvas = document.querySelector("canvas");
const signatureSaveButton = document.getElementById("saveSignature");
const signatureResetButton = document.getElementById("resetSignature");
const signatureError = document.getElementById("signatureError");
const signatureInput = document.getElementById("signatureInput");
// Initialize a new signaturePad instance.
var signaturePad = new SignaturePad(canvas);
// Clear signature pad.
signatureResetButton.addEventListener("click", function(event) {
signaturePad.clear();
});
// Save signature pad as data url.
signatureSaveButton.addEventListener("click", function(event) {
if (signaturePad.isEmpty()) {
signatureError.style.display = "block";
} else {
signatureUrl = signaturePad.toDataURL();
signatureInput.value = signatureUrl;
}
});
// Validate registration tab before moving to the next tab
$("#register-form").validate({
rules: {
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 8,
},
password_confirmation: {
required: true,
minlength: 8,
equalTo: "#password"
},
full_name: {
required: true
},
nric: {
required: true
},
address_1: {
required: true
},
address_2: {
required: true
},
address_3: {
required: true
},
postcode: {
required: true
},
city: {
required: true
},
state: {
required: true
},
contact_number_home: {
required: true
},
contact_number_mobile: {
required: true
},
existing_customer: {
required: true
},
signatureError: {
required: true
},
},
messages: {
email: {
required: "Please enter an email",
email: "The email is not valid"
},
password: {
required: "Please enter a password",
minlength: "Password must be minimum of 8 characters"
},
password_confirmation: {
required: "Please confirm your password",
minlength: "Passmust must be minimum of 8 characters",
equalTo: "Password must be same as above"
},
full_name: {
required: "Please enter your full name"
},
nric: {
required: "Please enter your identity card number"
},
address_1: {
required: "Please enter your address"
},
address_2: {
required: "Please enter your address"
},
address_3: {
required: "Please enter your address"
},
postcode: {
required: "Please enter your postcode"
},
city: {
required: "Please select your city"
},
state: {
required: "Please select your state"
},
contact_number_home: {
required: "Please enter your home number"
},
contact_number_mobile: {
required: "Please enter your mobile number"
},
signatureError: {
required: "Please provide your signature"
},
}
});
// validate fields in 1st tab
$('#next-btn').click(function() {
if ($("#register-form").validate().element('#email') && $("#register-form").validate().element('#password') && $("#register-form").validate().element('#password-confirm')) {
nextTab.find('a').trigger('click');
} else {}
});
// validate fields in 2nd tab
$('#next-btn2').click(function() {
if ($("#register-form").validate().element('#full_name') && $("#register-form").validate().element('#nric') && $("#register-form").validate().element('#address_1') && $("#register-form").validate().element('#address_2') && $("#register-form").validate().element('#address_3') && $("#register-form").validate().element('#postcode') &&
$("#register-form").validate().element('#city') && $("#register-form").validate().element('#state') && $("#register-form").validate().element('#contact_number_home') &&
$("#register-form").validate().element('#contact_number_mobile') && $("#register-form").validate().element('#existing_customer')
) {
nextTab.find('a').trigger('click');
} else {}
});
// validate signature input in 3rd tab
$('#submit').click(function() {
if ($("#register-form").validate().element('#signatureError')) {
alert("Success");
} else {
alert("Failure");
}
});

If you are using signature_pad by Szymon Nowak then it looks like you set it up correctly.
Edit: OK, I got the signature field to be part of validation. You need to not ignore hidden fields.
Do not validate the error message, LOL. Validate the actual field.
Also, I added a custom validator to handle validating the signature pad, but since it sets the value of the hidden signature field when you hit save, we only need to validate the signature.
Helpful links
https://jqueryvalidation.org/documentation/
https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
jQuery Validate - Enable validation for hidden fields
Example
let $form = $("#register-form");
let canvas = document.querySelector('.signature-pad');
let signatureSaveButton = document.getElementById('saveSignature');
let signatureResetButton = document.getElementById('resetSignature');
let signatureInput = document.querySelector('input[name="signature"]');
// Initialize a new signaturePad instance.
let signaturePad = new SignaturePad(canvas);
// Clear signature pad.
signatureResetButton.addEventListener('click', function(event) {
signaturePad.clear();
signatureInput.value = '';
event.preventDefault();
return false; // prevent submission...
});
// Save signature pad as data url.
signatureSaveButton.addEventListener('click', function(event) {
let signatureBlank = signaturePad.isEmpty();
if (!signatureBlank) {
signatureUrl = signaturePad.toDataURL();
signatureInput.value = signatureUrl;
$("div.error-messages span").html(''); // Clear messages
}
$(signatureInput).valid(); // Call validation on the field after hitting "Save"
event.preventDefault();
return false; // prevent submission...
});
// Not used, because this field has no name. Also, we want to use this
// to set the underlying (hidden) signature field...
$.validator.addMethod('signaturePresent', function(value, element) {
console.log('Checking...');
return this.optional(element) || signaturePad.isEmpty();
}, "Please provide your signature...");
// Validate registration tab before moving to the next tab
$form.validate({
ignore: [], // This is important! We want to validate hidden fields.
rules: {
signature: {
required: true
}
},
messages: {
signature: {
required: "Please provide your signature"
}
},
submitHandler: function(form) {
$("div.error-messages span").html(''); // Clear messages
console.log('Submitting form...');
//form.submit(); <-- UNCOMMENT TO ACTUALLY SUBMIT
},
invalidHandler: function(event, validator) {
console.log('INVALID!');
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error-messages span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
});
body {
padding: 2em;
}
.signature-pad {
display: block;
border: thin solid grey;
margin: 0 auto;
margin-bottom: 0.5em;
}
.hidden {
display: none !important;
}
form .error {
color: #F00;
}
.error-messages {
text-align: center;
font-size: smaller;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/1.5.3/signature_pad.min.js"></script>
<form id="register-form">
<div class="row">
<div class="col-md-6 text-center">
<label for="signatureInput">Signature</label>
</div>
<div class="form-group text-center">
<canvas class="display-block signature-pad" style="touch-action: none;"></canvas>
<div>
<button id="resetSignature" class="btn btn-sm" style="background-color: lightblue;">Reset</button>
<button id="saveSignature" class="btn btn-sm" style="background-color: #fbcc34;">Save</button>
</div>
<input type="hidden" name="signature" id="signatureInput">
</div>
</div>
<div class="row">
<div class="col-md-6 text-right">
<input type="hidden" name="registrationFor" value="customer">
<button type="submit" id="submit" class=" btn next-button bjsh-btn-gradient text-right">Sign Up</button>
</div>
</div>
</form>
<div class="error-messages"><strong>Messages:</strong><br/><span></span></div>

Related

Error text is not being displayed for function result

I've successfully used the definition on other pages before. Basically it should make the field required, but fail if only whitespace is entered (by default typing i.e. a single space causes the required check to pass). I tossed an alert in just to see when the handler is fired as well as the value of this at that time. It's fired when I expect it, and the value is as I expect it. It should be returning false but apparently it isn't because the error isn't being displayed. If I remove that depends function and just have required: true, it correctly displays the error when the user leaves the field. What's going on?
ContactName: {
required: {
depends: function() {
alert("'" + $(this).val() + "'");
if ($.trim($(this).val()).length === 0) {
$(this).val($.trim($(this).val()));
return false;
}
return true;
}
},
maxlength: 100
}
You can change the rule for ContactName like (for details take a look to rules examples):
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
The snippet:
$("#commentForm").validate({
rules: {
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
},
messages: {
ContactName: "Please enter your contact name"
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="ContactName">Name</label>
<input id="ContactName" name="ContactName" type="text">
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>

How to validate a form

I do have a html form which takes username and password as input . On button click , wrote a js function which would hit the api asynchronously . Before that , how would i validate it
<form>
<div><label id="resultString"></label></div>
<fieldset>
<legend>Login</legend>
Username: <input type="text" id="username"><br><br>
Password: <input type="password" id="password"><br><br>
<input type="button" onclick="submitdetails();" value="Login">
</fieldset>
</form>
My js function is :
function submitdetails() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var params = JSON.stringify({ username: username, password: password });
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200)
document.getElementById("resultString").innerHTML = xmlhttp.responseText;
else
document.getElementById("resultString").innerHTML = "Error";
}
};
xmlhttp.open("POST","http://127.0.0.1:8000/login/",true);
xmlhttp.send(params);
}
<form id='form' name='form' method='post' action=''>
<div><label id="resultString"></label></div>
<fieldset>
<legend>Login</legend>
Username: <input type="text" id="username" name="username"><br><br>
Password: <input type="password" id="password" name="password"><br><br>
<input type="button" value="Login">
</fieldset>
</form>
And this is the validator plugin code:
$(document).ready(function() {
$('#form').validate({
rules: {
username: {
required: true
},
password: {
required: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
success: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
}
});
});
refer: https://jqueryvalidation.org/
DEMO
THINGS TO REMEMBER
Your form should have a name and id
I say, give name and id for all fields as well
Use submit handler to do the call you did on onclick
<script>
function submitdetails() {
var username = $("#username").val();
var password = $("#passwords").val();
if(username==""||password=="")
{
alert("please fill");
}
var params = JSON.stringify({ username: username, password: password });
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200)
document.getElementById("resultString").innerHTML = xmlhttp.responseText;
else
document.getElementById("resultString").innerHTML = "Error";
}
};
xmlhttp.open("POST","http://127.0.0.1:8000/login/",true);
xmlhttp.send(params);
}
using following conditions
if(username ==null || username =="")
{
document.getEelementById("showerr").innerHTML = "is empty";
}
if(password==null || password =="" password.length < 6)
{
document.getEelementById("showerr").innerHTML = "must 6 or above characters";
}
HTML :
<span id="showerr"></span>
using regular expression you can validate
http://jsfiddle.net/ghvj4gy9/embedded/result,js/
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["email"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<br/>
email: <input type="text" name="email">
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
But its easy to use use jQuery validate plugin
Demo : https://jqueryvalidation.org/files/demo/
Documentation : https://jqueryvalidation.org/documentation/
sample code -
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});

Jquery - Form doesn't submit

I'm trying to submit my form through Jquery, but the submit part of my code just doesn't work! And I can't see what's wrong with it.
<?php
if(!isset($_SESSION["useridentity"])){
die(header("Location:index.php"));
}
include("actions/connect.php");
$q = "SELECT username FROM users WHERE useridentity = '".$_SESSION["useridentity"]."'";
$r = mysql_query($q,$con);
$f = mysql_fetch_array($r);
?>
<div class="absolutedialog" id="login">
<form class="loginform" id="loginform" name="loginform" method="POST" action="actions/login.php">
<div class="label">
Welcome back, <b><?php echo $f["username"]; ?></b>. Please, type your password to confirm your identity.
</div>
<input class="loginformpassword" id="password" type="password" name="pass" maxlength="32"/>
<div id="passwordfail"></div>
<input class="regularbutton" id="submit" type="button" value="Submit"/>
<button class="grayregularbutton" id="gobacktoconsole" type="button">Go back</button>
</form>
</div>
<div class="blackoverlay"></div>
<script>
$(document).ready(function() {
$('#login').fadeIn(1000);
$('.blackoverlay').fadeIn(500);
//Destroy $_SESSION variables and go back to console
$('#gobacktoconsole').on('click',this, function(e) {
$(".absolutedialog").fadeOut(500);
$(".blackoverlay").fadeOut(1000);
window.setTimeout(
function() {
window.location.href="actions/logout.php";
},
1000
);
});
//Submit validations
$('#submit').on('click',this, function(e){
if($("#password").val() == "")
$("#passwordfail").html("Please, type your password");
else{
$("form#loginform").submit();
$(".absolutedialog").fadeOut(500);
$(".blackoverlay").fadeOut(1000);
}
});
//Clear password message error when something is typed in the password input
$('#password').on('keyup',this, function(e) {
$("#passwordfail").html("");
});
//Prevent default submit on enter, and click #submit button instead in order to execute validations
$('#loginform').bind("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if(code == 13){
e.preventDefault();
$("#submit").click();
}
});
});
</script>
I tried adding return false; below $("form#loginform").submit(); but doesn't works. Am I missing something? Please, help!
Sorry for the lack of details; if you need me to add some more, please ask.
You have this element:
<input class="regularbutton" id="submit" type="button" value="Submit"/>
When you say
$("form#loginform").submit();
THe brpwser is assuming you're calling it, not the submit() method of the form object. Just change the id to something else.
<input class="regularbutton" id="submitButton" type="button" value="Submit"/>
The nastiest thing ever! Hope this helps.
I have seen many times problems about form submitting and form validation and I have found that the best way to do it is by using a simple open source jquery plugin such as jquery.validate.js.
This is an example about preventing default submit and posting data successfully to php file.
First you have to get these open source framework and you can use them whenever you want.
Files are three scripts :
<script src="js/jquery.min.js></script>
<script src="js/bootstrap.min.js"></script> <!-- open source framework twitter bootstrap -->
and one css file :
<link href="bootstrap/bootstrap.min.css" rel="stylesheet" media="screen">
example of code :
<form method="post" action="php/inscriptionAction2.php" class="form-horizontal" name="register" id="register">
// code of site inscription : name , email , password , confirmed password ....
<div class="form-group">
<div class="col-xs-offset-3 col-xs-9">
<div class="form-actions">
<input type="submit" class="btn btn-primary" name="newsubmit" id="newsubmit" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</div>
</form>
and this is a simple script
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
});
$('#loginForm').validate({
rules: {
name: {
minlength: 2,
lettersonly:true,
required: true
},
lname: {
minlength: 2,
lettersonly:true,
required: true
},
username: {
lettersonly:true,
minlength: 2,
required: true
},
email: {
required: true,
email: true,
remote: {
url: '/setup/verify_email/',
cache: false
}
},
password: {
required: true,
minlength: 5,
maxlength: 250
},
password2: {
equalTo: '#password'
},
gender: {
required: true
}
},
messages: {
name: {
required:"Please enter your first name",
minlenght:"Your first name must consist of at least {0} characters",
lettersonly: "Letters only please"
},
lname: {
required:"Please enter your last name",
minlenght:"Your last name must consist of at least {0} characters",
lettersonly: "Letters only please"
},
username: {
lettersonly: "Letters only please",
required: "Please enter a username",
minlength: "Your username must consist of at least {0} characters"
},
email: {
required:"Please enter your email address",
email:"Please enter a valid email adress",
url:"Please enter a valid url",
cache:""
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least {0} characters long",
maxlength: "Your password must be less than {0} characters long"
},
password2: {
equalTo: "Please enter the same passwords"
},
postal_code: "Please enter a valid zip code",
timezones: "Please select a time zone",
mp: "Please enter a valid mobile number. Only numbers please.",
gender: "Please select a gender",
dob: "Please enter a valid Date of Birth in mm/dd/yyyy format."
},
highlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('error').addClass('success');
},
success: function (label) {
$(label).closest('form').find('.valid').removeClass("invalid");
},
errorPlacement: function (error, element) {
element.closest('.control-group').find('.help-block').html(error.text());
}
}).cancelSubmit=true; // to block the submit of this plugin and call submit to php file
By using two powerful frameworks, Twitter Bootstrap and jQuery , you can make your work faster and more professional.
For more details you can have a look at their documentation.
First you should import jquery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
second change the id value of the button to anything else and will work, you may need to set timeout before submitting in order to delay the submit after the fadeout effect

jQuery validation unable to validate my information

I need to do a validation for my username during registration, unfortunately I'm not able to get any information from the screen and there is no response when I clicked submit button.
UPDATED
This is the login and signup script that I doing, but I'm unable to display my error message and also display incorrect css style when doing the checking.
Here is the screencast http://www.screencast.com/t/hQdRev1HOnh
<script>
$(document).ready(function() {
//* boxes animation
form_wrapper = $('.login_box');
function boxHeight() {
form_wrapper.animate({marginTop: (-(form_wrapper.height() / 2) - 24)}, 400);
}
;
form_wrapper.css({marginTop: (-(form_wrapper.height() / 2) - 24)});
$('.linkform a,.link_reg a').on('click', function(e) {
var target = $(this).attr('href'),
target_height = $(target).actual('height');
$(form_wrapper).css({
'height': form_wrapper.height()
});
$(form_wrapper.find('form:visible')).fadeOut(400, function() {
form_wrapper.stop().animate({
height: target_height,
marginTop: (-(target_height / 2) - 24)
}, 500, function() {
$(target).fadeIn(400);
$('.links_btm .linkform').toggle();
$(form_wrapper).css({
'height': ''
});
});
});
e.preventDefault();
});
//* validation
$('#login_form').validate({
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
username: {required: true, minlength: 3},
password: {required: true, minlength: 3}
},
highlight: function(element) {
$(element).closest('div').addClass("f_error");
setTimeout(function() {
boxHeight()
}, 200)
},
unhighlight: function(element) {
$(element).closest('div').removeClass("f_error");
setTimeout(function() {
boxHeight()
}, 200)
},
errorPlacement: function(error, element) {
$(element).closest('div').append(error);
}
});
$('#reg_form').validate({
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
reg_username: {
required: true,
minlength: 3,
remote: {
url: "http://127.0.0.1/check_username.php",
type: "post"
}
},
message: {
reg_username: {remote: jQuery.format("{0} is already in use")}
},
reg_password: {required: true, minlength: 3}
},
highlight: function(element) {
$(element).closest('div').addClass("f_error");
setTimeout(function() {
boxHeight()
}, 200)
},
unhighlight: function(element) {
$(element).closest('div').removeClass("f_error");
setTimeout(function() {
boxHeight()
}, 200)
},
errorPlacement: function(error, element) {
$(element).closest('div').append(error);
}
});
});
</script>
And this is my username checking source code. Although i change the return the string result I won't able to show my error message.
include('../inc/dbconn.php');
if (isset($_POST['reg_username'])) {
$reg_username = mysql_real_escape_string($_POST['reg_username']);
$check_for_username = mysql_query("SELECT username FROM customers_register WHERE username='$reg_username'");
if (mysql_num_rows($check_for_username)) {
echo 'false';
} else {
//No Record Found - Username is available
echo 'true';
}
}
Here one of my part of javascript
$('#reg_form').validate({
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
reg_username: {required: true, minlength: 3, remote:"check_username.php"},
reg_password: {required: true, minlength: 3}
},
message: {
reg_username: {remote: jQuery.format("{0} is already in use")}
},
highlight: function(element) {
$(element).closest('div').addClass("f_error");
setTimeout(function() {
boxHeight()
}, 200)
},
unhighlight: function(element) {
$(element).closest('div').removeClass("f_error");
setTimeout(function() {
boxHeight()
}, 200)
},
errorPlacement: function(error, element) {
$(element).closest('div').append(error);
}
});
and this is my check_username.php
<?php
include('../inc/dbconn.php');
if (isset($_POST['reg_username'])) {
$reg_username = mysql_real_escape_string($_POST['reg_username']);
$check_for_username = mysql_query("SELECT username FROM customers_register_user WHERE username='$reg_username'");
if (mysql_num_rows($check_for_username)) {
echo "TRUE";
} else {
//No Record Found - Username is available
echo "FALSE";
}
}
?>
And this is html source code
<form method="post" id="reg_form" style="display:none">
<div class="top_b">Sign up</div>
<div class="alert alert-login">
By filling in the form bellow and clicking the "Sign Up" button, you accept and agree to <a data-toggle="modal" href="#terms">Terms of Service</a>.
</div>
<div id="terms" class="modal hide fade" style="display:none">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Terms and Conditions</h3>
</div>
<div class="modal-footer">
<a data-dismiss="modal" class="btn" href="#">Close</a>
</div>
</div>
<div class="cnt_b">
<? echo '<input type = "hidden" name = "client_mac" value = "' . $client_mac . '">'; ?>
<div class="formRow">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" id="reg_username" name="reg_username" placeholder="Username" />
</div>
</div>
<div class="formRow">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span><input type="password" id="reg_password" name="reg_password" placeholder="Password" />
</div>
</div>
<div class="formRow">
<div class="input-prepend">
<span class="add-on">#</span><input type="text" disabled="disabled" id="email" placeholder="<?= $email ?>" />
</div>
<small>The e-mail address is not made public and will only be used if you wish to receive a new password.</small>
</div>
</div>
<div class="btm_b tac">
<button class="btn btn-inverse" name="oprf" value="signup" type="submit">Sign Up</button>
</div>
</form>
It seems your jquery code is fine. Can you please debug your script like this:-
<?php
error_reporting(E_ALL);
include('../inc/dbconn.php');
if (isset($_POST['reg_username'])) {
$reg_username = mysql_real_escape_string($_POST['reg_username']);
$check_for_username = mysql_query("SELECT username FROM customers_register_user WHERE username='$reg_username'") or die(mysql_error());
// If 0 reocrd found then username available
if (mysql_num_rows($check_for_username) > 0) {
echo 0;
} else {
//No Record Found - Username is available
echo 1;
}
}
?>
Quote OP:
"This is the latest update seem I can get the TRUE and FALSE from the validation but the problem is although I have enter the value it still pop out the error and I won't able to submit my registration."
Your code...
if (mysql_num_rows($check_for_username)) {
echo "TRUE";
} else {
//No Record Found - Username is available
echo "FALSE";
}
Your true/false logic is completely backwards. In the jQuery Validate plugin, if a method returns true it means the element passed validation and false means the element failed validation (triggers the error message).
You are echoing "TRUE" when the username is already in your database, however, you should be echoing "FALSE" to indicate that this field has failed validation.
EDIT:
As per documentation:
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements...
http://jqueryvalidation.org/remote-method/

Jquery Validation on cloned elements

I am using the following JQuery validation:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I have the following element:
<div class="form-item">
<label for="Reference_name" class="required">Name: <span class="required">*</span></label>
<input name="Reference[name][]" class="form-input validate {validate:{required:true,minLength:2,messages:{required:'Your name is required',minLength:'Your name is too short'}}}" id="Reference_name" type="text">
</div>
I have cloned the element but the validation is only appearing on the first element. I would like it to validate against the second too and show the error message label.
Can someone help with this please.
elements must be unique
<label for="Reference_name" class="required">Name:<span class="required">*</span></label>
<input type="text" id="Reference_name" name="Reference[Name]" id="Reference_name" required="required" maxlength="255" />
File Js
$(document).ready(function() {
validate_form();
});
function validate_form() {
$("#id_of_your_form").validate({
rules: {
'Reference_name': {
required:true,
minlength: 2,
}
},
},
messages: {
'Reference_name': {
required:"Your name is required",
minLength:'Your name is too short'
},
}
});
}
if you want to compare two fields
http://docs.jquery.com/Plugins/Validation/Methods/equalTo#other
Put your validation function in a global variable like this:
var validate_form_function = function(){
if($(".app-form").length > 0){
$('.app-form').validate({
rules: {
comment_message: {
required: true,
minlength: 2
}
},
messages: {
comment_message: {
required: "Your message",
minlength: "Your message"
}
}
});
}
};
Then revalidate your cloned form with the function like this :
validate_form_function();

Categories

Resources