I have 2 separate functions working that use 2 different buttons, however I want to put them together for so that both functions are triggered simultaneously under one button.
I have a user registration form, and I have one function that sends the data into the database, and the other function checks if the username is existing or not.
What I need is for when the user submits the form, the form should not be submitted if the username already exists, thus an alert should appear saying for example "username taken, please try another". Nevertheless, if username has not been taken, then submit the form.
Can someone shed some light on how I can go about this and put both these functions together for the same button?
Register Function -
function registerUser() {
var Username = document.getElementById("txtusername").value;
var Firstname = document.getElementById("txtfirstname").value;
var Lastname = document.getElementById("txtlastname").value;
var Email = document.getElementById("txtemail").value;
var Password = document.getElementById("txtpassword").value;
var Confirmpass = document.getElementById("passwordconfirm").value;
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
db.transaction(function(tx) {
NewUser(tx, Username, Firstname, Lastname, Email, Password, Confirmpass);
}, errorRegistration, successRegistration);
}
function NewUser(tx, Username, Firstname, Lastname, Email, Password, Confirmpass) {
var _Query = ("INSERT INTO SoccerEarth(UserName, FirstName, LastName, Email, Password, CPass) values ('"+ Username +"','"+ Firstname +"','"+ Lastname +"','"+ Email +"', '"+ Password +"', '"+ Confirmpass +"')");
alert(_Query);
tx.executeSql(_Query);
}
function errorRegistration(error) {
navigator.notification.alert(error, null, "Got an error mate", "cool");
}
function successRegistration() {
navigator.notification.alert("User data has been registered", null, "Information", "ok");
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#page4" );
}
Check username in database function-
function CheckUser()
{
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
db.transaction(UserDB, errorCB);
}
function UserDB(tx)
{
alert("user check");
var User = document.getElementById("txtusername").value;
tx.executeSql("SELECT * FROM SoccerEarth WHERE UserName='" + User + "'", [], renderUser);
}
function renderUser(tx,results) {
if (results.rows.length > 0) {
navigator.notification.alert("Username is taken, please try again.");
}
else
{
navigator.notification.alert("Username available!");
}
HTML -
<form id="form1" data-ajax="false">
<div data-role="fieldcontainer">
<label for="txtusername" data-theme="d">Username:</label>
<input type="text" id="txtusername" name="txtusername" maxlength="12" placeholder="Enter Username"/>
</div>
<div data-role="fieldcontainer">
<label for="txtfirstname" data-theme="d">First Name:</label>
<input type="text" id="txtfirstname" name="txtfirstname" placeholder="Enter First Name"/>
</div>
<div data-role="fieldcontainer">
<label for="txtlastname" data-theme="d">Last Name:</label>
<input type="text" id="txtlastname" name="txtlastname" placeholder="Enter Last Name"/>
</div>
<div data-role="fieldcontainer">
<label for="txtemail" data-theme="d">Email:</label>
<input type="email" id="txtemail" name="txtemail" placeholder="Enter Enter Email"/>
</div>
<div data-role="fieldcontainer">
<label for="txtpassword" data-theme="d">Password:</label>
<input type="text" id="txtpassword" name="txtpassword" maxlength="12" placeholder="Enter Password"/>
</div>
<div data-role="fieldcontainer">
<label for="passwordconfirm" data-theme="d">Confirm Password:</label>
<input type="text" id="passwordconfirm" name="passwordconfirm" maxlength="12" placeholder="Confirm password"/>
</div>
<br>
<input type="submit" value="Register User">
Input Validations (JQUERY) -
$('#form1').submit(function (e) {
e.preventDefault();
}).validate({
rules: {
txtusername: {
required: true
},
txtfirstname: {
required: true
},
txtemail: {
required: true
},
txtpassword: {
required: true
},
passwordconfirm: {
required: true
}
},
messages: {
txtusername: {
required: "Please enter your Username."
},
txtfirstname: {
required: "Please enter your First Name."
},
txtemail: {
required: "Please enter your Email."
},
txtpassword: {
required: "Please enter your Password."
},
passwordconfirm: {
required: "Please enter your password again."
}
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().prev());
},
submitHandler: function (form, user) {
registerUser(form);
return false;
}
});
I can see in your code that you check if the username is available, so you can use the event onchange
<input type="text" onchange="CheckUser()" id="txtusername" name="txtusername" maxlength="12" placeholder="Enter Username"/>
so when the user write some your function CheckUser() is activated, after that you can use normally , inside of
if (results.rows.length > 0) {
navigator.notification.alert("Username is taken, please try again.");
} else {
//add event click only if is available your username
navigator.notification.alert("Username available!");
element = document.getElementById("btnSend");
element.addEventListener("click", registerUser())
}
and write your input submit with this id btnSend
<input id="btnSend" type="submit" value="Register User">
So in this way you validate if the username is available only in this case you add RegisterUser() for your submit
last but not least be more careful because you wrote code in your JS (Query for DB) and this can be affecty your security
Create new function which call this 2 functions
function newfunction()
{
// you need to return true/false from check user function
if(CheckUser())
{
registerUser();
}
}
and call this on onclick
<input type="submit" value="Register User" onclick="newfunction()">
Use a onsubmit event to handle the registration
<form id="form1" data-ajax="false" onsubmit="doSubmit();">
and javascript function will look like
function doSubmit(){
// check if the user exists. Return a boolean value to return the status
var userExists = checkUser();
// if user exists, return false to protect form from submitting.
if(userExists){
return false;
}
// if user does not exists, register the user
registerUser();
}
Related
My html code like this :
<form class="validatedForm" id="commentForm" method="get" action="">
<fieldset>
<input name="password" id="password" />
<input name="password_confirmation" />
</fieldset>
</form>
<button>Validate</button>
My javascript code to validate with jquery validate like this :
jQuery('.validatedForm').validate({
rules: {
"password": {
minlength: 6
},
"password_confirmation": {
minlength: 6,
equalTo : "#password"
}
},
messages: {
"password": 'Please enter a password, minimal 6 characters',
"password_confirmation": 'Please confirm your password'
},
});
Demo and full code like this : http://jsfiddle.net/oscar11/fEZFB/609/
If user input password : abcdef, then click button validate, there exist messsage : "Please confirm your password"
If user input password confirmation : ghijkl, there exist message : "Please confirm your password"
I want to change the message if user input password confirmation not same
The message like this : "confirm your password is not the same"
So there exist two message :
If user not input password confirmation, the message : "Please confirm your password"
If user input password confirmation, but not same with password, the message : "confirm your password is not the same"
How can I do it?
I think this will cover what you're looking for. You aren't limited to one message per input - you can set one for each rule on each input. I added a break in your HTML to make it more readable.
<form class="validatedForm" id="commentForm" method="get" action="">
<fieldset>
<input name="password" id="password" /><br/>
<input name="password_confirmation" id="password_confirmation" />
</fieldset>
</form>
<button>Validate</button>
Updated script:
jQuery('.validatedForm').validate({
rules: {
"password": {
minlength: 6,
required: true
},
"password_confirmation": {
equalTo: "#password"
}
},
messages: {
"password": {
minLength: "Password must be at least 6 charachters",
required: "Password is required."
},
"password_confirmation": {
equalTo: "The password and confimation fields don't match"
}
},
});
$('button').click(function () {
console.log($('.validatedForm').valid());
});
I added a required rule to the password so clicking validate with a blank form generates a message. I removed the minlength on the confirmation- it only needs to be equal to the password, and it has a minlength. Too short of a password has its own message, and when the password is long enough you'll get a different message when the confirmation field is empty or otherwise not equal to the password. You can see it in the fiddle here: http://jsfiddle.net/oscar11/fEZFB/609/
I have basic html and want to validate the fields with jQuery validator so I have less validation on php level. The form validates if all fields are empty and prevents submission to php but as soon as I complete 1 input the form sumits (even if all other fields are blank). All fields are required so I'm stumped - please help!
After some of your advice I have redone my validation on php level but it has the exact same effect. If all the fields are empty the validation works, as soon as 1 field is filled in the form submits.
jQuery: I ran it through JSLint and it yielded no errors - unbelievable right?!
$().ready(function () {
"use strict";
$('#register').validate({
rules: {
firstname: {
required: true,
maxLength: 40
},
lastname: {
required: true,
maxLength: 40
},
email: {
required: true,
maxLength: 64,
email: true
},
password: {
required: true,
minLength: 6,
maxLength: 32
},
confirmPassword: {
required: true,
equalTo: "#password"
},
rsaid: {
required: true,
digits: true
}
},
messages: {
firstname: {
required: "Please enter your first name.",
maxLength: "Your first name cannot exceed 40 characters."
},
lastname: {
required: "Please enter your last name.",
maxLength: "Your last name cannot exceed 40 characters."
},
email: {
required: "Please enter your email address.",
maxLength: "Your email address cannot exceed 64 characters.",
email: "The email format provided is invalid."
},
password: {
required: "Please enter a password.",
minLength: "Your password must contain at least 6 characters.",
maxLength: "Your password cannot contain more than 32 characters."
},
confirmPassword: {
required: "Please confirm your password.",
equalTo: "Your passwords do not match!"
},
rsaid: {
required: "Please enter a valid RSA id number.",
//exactLength: "Your ID number must contain 13 characters!",
digits: "Your ID number must consist of numerals only!"
}
},
errorContainer: $('#errorContainer'),
errorLabelContainer: $('#errorContainer ul'),
wrapper: 'li'
});
});
html: Shouldn't be necessary but just in case :)
<div class="registrationForm">
<form id="register" action="php/insert.php" method="post">
<input type="text" id="firstname" name="firstname" placeholder="First Name" value="" class="radius mini" />
<input type="text" id="lastname" name="lastname" placeholder="Last Name" value="" class="radius mini"/>
<input type="text" id="email" name="email" placeholder="Your Email" value="" class="radius" />
<input type="password" id="password" name="password" placeholder="New Password" value="" class="radius" />
<input type="password" id="confirmPassword" name="confirmPassword" placeholder="Confirm Password" value="" class="radius" />
<input type="text" id="rsaid" name="rsaid" placeholder="RSA ID Number" value="" class="radius" />
<button class="radius title" name="signup">Sign Up for SFC</button>
</form>
</div>
PHP code: This contains code for only the first 3 fields as password validation is long and irrelevant. The code returns no errors on phpcodechekcer.com.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is required";
} else {
$firstname = mysqli_real_escape_string($link, $_POST['firstname']);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last name is required";
} else {
$lastname = mysqli_real_escape_string($link, $_POST['lastname']);
}
if (empty($_POST["email"])) {
$emailErr = "Email address is required";
} else {
if (!isValidEmail($_POST["email"])) {
$emailErr = "Email address is invalid";
} else {
$email = mysqli_real_escape_string($link, $_POST['email']);
}
}
}
better make validation on server side, if your client turn off javascript on browser then all data will send to server without any validation
It's to be need jquery file link on header of html.
Perhaps it's because you are not using fieldset enclosing?
On the other side, you may look towards plain HYML5 validation.
Having some trouble getting validation to work for Email and Phone on an input field.
Basically I'm after validation on the email input when it is selected. Phone validation - mainly to check for numbers used.
I found jQuery Validate and referenced that in my demo.
This is my first time to Reg Ex Validation and got a little confused so was hoping someone could help me on that front.
The phone validation is working however, I can't seem to figure out how to meet the requirements of the field when testing. It's also asking email as a required field.
Ultimately, a user has to input either a valid email or phone number so validation or error handling will need to be done for that too which I can do.
DEMO HERE
Here is my jQuery:
var ebuForm = {
init : function() {
ebuForm.showInput();
ebuForm.validatePhone();
},
showInput : function(e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function(){
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if($(this).val() =="email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
emailRadio.prop('checked', true).trigger("change");
},
validatePhone : function() {
$('#myform').validate({
rules: {
phone: {
phoneUS: true,
required: true
}
},
submitHandler: function(form) { // for demo
alert('valid form');
return false;
}
});
}
};
$(function() {
ebuForm.init();
});
Working Fiddle Example: http://jsfiddle.net/775X2/56/
Your HTML:
<form id="myform">
<div class="grid4">
<input type="radio" checked="checked" tabindex="50" class="left" name="x" id="email" value="email" />
<label for="email" class="left marginRight20">Email</label>
<input type="radio" tabindex="60" class="left" name="x" id="phone" />
<label for="phone" class="left">Phone</label>
<br />
<input type="text" class="email-input" name="emailer" placeholder="Email Address" />
<input type="text" class="phone-input" name="phone" placeholder="Phone Number" />
</div>
</form>
Validation Documentation
Some jQuery:
var ebuForm = {
init: function () {
ebuForm.showInput();
ebuForm.validatePhone();
},
showInput: function (e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function () {
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if ($(this).val() == "email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
emailRadio.prop('checked', true).trigger("change");
},
validatePhone: function () {
$('#myform').validate({
rules: {
phone: {
phoneUS: true,
required: true
},
emailer: {
required: true,
email: true
},
},
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
}
};
$(function () {
ebuForm.init();
});
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
I have a simple login form and have jQuery validate replacing the field labels when there's an error to display. The problem is that, once the error is cleared, the label disappears. I would like to find a way to revert back to the previous label's content, or rebuild that label when the field is valid...
Here's my code:
$(document).ready(function(){
$("#login").validate({
errorPlacement: function(error, element) {
element.prev().replaceWith(error);
},
rules: {
"email": {
required: true,
email:true,
},
"password": {
required: true,
minlength: 6
}
},
messages: {
email: {
required: "Please enter your email address.",
email: "Please enter a <u>valid</u> email address"
},
password: {
required: "Please enter your password.",
minlength: "Please enter a password with 6 characters or more."
}
},
});
});
And the HTML:
<form name="login" id="login" method="post" action="authenticate.php">
<p>
<label for="email">Email Address:</label>
<input type="text" name="email" id="email" class="required email" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" class="required" />
</p>
<p>
<input type="submit" value="Log In" id="submit" />
</p>
In essence, when the user submits the form, if there's no data in the Email field, then the label for email gets replaced with the error. But once it has valid input, I want to put back the original label.
Thanks in advance for any suggestions,
Z
I actually worked out a compromise whereby, instead of replacing the previous label with the error label, I'm appending a span into that label using error.appendTo(element.prev()) and errorElement: "span". Here's the new code:
$(document).ready(function(){
$("#login").validate({
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.prev());
//element.prev().replaceWith(error);
},
rules: {
"email": {
required: true,
email:true,
},
"password": {
required: true,
minlength: 6
}
},
messages: {
email: {
required: " is Required",
email: " is Improperly Formatted"
},
password: {
required: " is Required",
minlength: " is not Long Enough"
}
},
});
});
It's less than ideal, but at least when the span appears, the error code is where I want it to be, and when it disappears, the label remains intact. I just made it so the label and the error complete each other like sentences... Eg, "Email Address" " is required." or "Email Address" " is not properly formatted."
Thanks to everybody that contributed here,
Z
You can remove
errorPlacement: function(error, element) {
element.prev().replaceWith(error);
},
and the messages should appear beside the textboxes instead.
You can try to removeChild(label),and attach a new one to it when the error accur. Toggling the label seems to make sence