I'm trying to get an error message to show when my fields are missing input. Once both are filled in I want a success message to show in place of #error.
Not sure why I'm not getting any message currently.
$("input[type='button']").click(function() {
$("form").validate({
rules: {
username: "required"
},
messages: {
username: "please enter a name"
}
});
alert("Submitted");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<form>
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="pw">Password:</label>
<input type="password" name="pw" id="pw">
</p>
<p>
<input type="button" value="Submit">
</p>
<!-- placeholder for response if form data is correct/incorrect -->
<p id="error"></p>
</form>
What about this ?
$("input[type='button']").click(function() {
if($("#username").val()==""){
$("#error").html("Please enter a name");
return;
}
if($("#pw").val()==""){
$("#error").html("Password required");
return;
}
alert("Submitted");
});
Related
I have a form I am trying to validate using JQuery Validate, which works fine. When the submit button is clicked, the submitHandler should 1. disable the button (to prevent multiple submissions) and 2. change the button text.
As is, the code works for validation but does not invoke the submitHandler.
I've looked over many threads on here, saying that the button must be type="submit", inside the <form> tags, etc. and cannot figure this out. The button is still able to be clicked multiple times.
Any help?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#freebottleform").validate({
rules: {
address : {
required: true
},
city : {
required: true
},
state : {
required: true
},
zipcode : {
required: true
},
phoneNumber : {
required: true,
phoneUS: true
},
},
//Specify the validation error messages here
messages: {
email: {
required: "Please enter email address",
email: "Please enter a valid email address"
},
phoneNumber: {
required : "Please enter your mobile number",
digits: "Please enter digits only"
}
},
submitHandler: function (form) {
$("#finalSubmit").attr("disabled", true);
$("#finalSubmit").html("Submitting... please wait.");
form.submit();
}
});
});
</script>
<!DOCTYPE html>
<html lang="en">
<div class="freebottleform">
<form method="post" id="freebottleform" name="freebottleform" action="p6.php">
Please enter your shipping details.<br>
<br>
Address:<br>
<input type="text" name="address" class="required" placeholder="Please enter your address."/><br>
<input type="text" name="address2" placeholder="Suite/Apt/Etc."/><br>
<br>
City:<br>
<input type="text" name="city" class="required" placeholder="Please enter your city."/><br>
<br>
State:<br>
<input type="text" name="state" class="required" placeholder="Please enter your state."/><br>
<br>
Zip Code:<br>
<input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode."/><br>
<br>
Phone Number:<br>
<input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number."/><br>
<br>
<label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
<br>
<button id="finalSubmit" type="submit" name="submit" value="final" >CONTINUE</button>
</form>
</div>
</html>
You can do your validation and disable the button on click event of button, at client side.
<script type="text/javascript">
$("#finalSubmit").click(function()
{
//do your validation and if correct then disable the button
$("#finalSubmit").attr("disabled", true);
//other work if any
}
);
</script>
1st of all instead of making validations with jQuery, make validations on server side like with PHP etc., and reflect the output on the display page.
An example here:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Site Title</title>
</head>
<body>
<h1>Form</h1>
<div class="message"></div>
<form method="post" action="" name="registrationForm">
First Name <input type="text" name="fname"><br>
Last Name <input type="text" name="lname"><br>
Phone <input type="text" name="phone"><br>
<input type="submit" value="Register" class="regbtn">
</form>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".regbtn").click(function(){
var form = document.registrationForm;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: "your-processing-page.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".regbtn").prop('disabled', true).val('Please wait...');
},
success: function(data){
$('.message').html(data).fadeIn();
$(".regbtn").prop('disabled', false).val('Register');
}
});
return false;
});
});
</script>
</body>
</html>
your-processing-page.php
<?php
$fname = (!empty($_POST['fname']))?$_POST['fname']:null;
$lname = (!empty($_POST['lname']))?$_POST['lname']:null;
$phone = (!empty($_POST['phone']))?$_POST['phone']:null;
if($_POST){
// Perform Checks Here
if(trim($fname) == ''){
echo "Please enter first name.";
}else if(trim($lname) == ''){
echo "Please enter last name.";
}else if((strlen($phone)) == 0){
echo "Please enter a phone number";
}else if((strlen($phone)) < 10){
echo "Phone number must not contain less than 10 digits.";
}else if((strlen($phone)) > 10){
echo "Phone number must not contain more than 10 digits.";
}else{
// If all checks are cleared perform your query
$stmt = $pdo->prepare("INSERT INTO members(mem_fname, mem_lname, mem_phone)VALUS(:fname, :lname, :phone)");
$stmt-> bindValue(':fname', $fname);
$stmt-> bindValue(':lname', $lname);
$stmt-> bindValue(':phone', $phone);
$stmt-> execute();
if($stmt){
echo "Success! User has been registered.";
}else{
echo "Sorry, something went wrong. Please refresh the page and try again!";
}
}
}
?>
That's a complete answer. Here:
Validation is done on server side using PHP (better method and must be followed).
jQuery disables submit button to prevent double submission after click.
jQuery changes button text value when submit button is pressed and changes back to default on successful return from form submission.
Note: The above is a fully working "standard" coding sample. That's how you should code. However, perform other necessary checks as per your need. Take the above coding only as a sample to frame your own code. Happy coding :)
Change the submit button name to something else because it overrides the submit() function on the form, then this code should work for you(Reference). ↓↓
$(document).ready(function() {
$("#freebottleform").validate({
rules: {
address: {
required: true
},
city: {
required: true
},
state: {
required: true
},
zipcode: {
required: true
},
phoneNumber: {
required: true,
// phoneUS: true,
digits: true
},
},
//Specify the validation error messages here
messages: {
email: {
required: "Please enter email address",
email: "Please enter a valid email address"
},
phoneNumber: {
required: "Please enter your mobile number",
digits: "Please enter digits only"
}
},
submitHandler: function(form) {
$("#finalSubmit").attr("disabled", true);
$("#finalSubmit").html("Submitting... please wait.");
setTimeout(function() {
form.submit();
}, 3000);
}
});
});
<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>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<div class="freebottleform">
<form method="post" id="freebottleform" name="freebottleform" action="p6.php">
Please enter your shipping details.<br>
<br> Address:
<br>
<input type="text" name="address" class="required" placeholder="Please enter your address." /><br>
<input type="text" name="address2" placeholder="Suite/Apt/Etc." /><br>
<br> City:
<br>
<input type="text" name="city" class="required" placeholder="Please enter your city." /><br>
<br> State:
<br>
<input type="text" name="state" class="required" placeholder="Please enter your state." /><br>
<br> Zip Code:<br>
<input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode." /><br>
<br> Phone Number:<br>
<input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number." /><br>
<br>
<label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
<br>
<button id="finalSubmit" type="submit" name="save" value="final">CONTINUE</button>
</form>
</div>
</html>
i am trying to use jQuery validate to validate a big form that i have cut in 3 different sections.
personal information
job information
additional information
is there a way for me to validate the content every time the user hits continue? and then when they get to the last section they can submit the ENTIRE form?
form
<form method="post" name="form" id="form" class="form">
<div class="section_one form-wrapper-top-margin active">
<div class="columns-2 float-left">
<input name="name" id="name" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="email" id="email" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_1"/>
</div>
</div>
<div class="section_two form-wrapper-top-margin">
<div class="columns-1 margin-0">
<input name="address" id="address" type="text" class="" value=""/>
</div>
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_2"/>
</div>
</div>
<div class="section_there form-wrapper-top-margin">
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="submit" type="submit" id="submitbtn" value="Send your message"/>
</div>
</div>
</div>
</div>
</form>
i dont put the jQuery code here because i dont know where to start. i know jQuery validate, validates an entire form, but i never seen it done by sections with out splitting it into 3 different forms.
Thanks for the help...
You can do like this also:-
$(".section_two").click(function(){
//Your code for validation of section one.
});
$(".section_three").click(function(){
//Your code for validation of section one and section two.
});
$("#submitbtn").click(function(){
//Your code for validation of section three.
});
Let me know if this helps.
I found the answer here:
jQuery button validate part of a form at a time
this is the code i used
var validator = $('#form').validate({
ignore: 'input.continue,input#submitbtn',
rules: {
name: {
required: true
},
email: {
required : true
},
date: {
required: true
},
},
messages: {
name: "Enter your name",
email: {
require: "Please enter a valid email address",
email: "Enter a valid email"
},
},
errorPlacement: function(error, element) { },
});
$('#continue1').on('click', function(){
var tab = $(".section_one.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-1080px'});
}
});
$('#continue2').on('click', function(){
var tab = $(".section_two.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-2160px'});
}
});
thanks for everyone's advise...
I want to create some popup that will tell user when he doesn't enter name, lastname, number or email.
HTML :
<div class="form-group">
<label class="label-block" for="cname" data-new-placeholder="What is your name?">Ime</label>
<input name="firstName" minlength="3" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block" for="cemail">Email</label>
<input name="ctct" type="email" required="required" required class="texbox">
</div>
</div>
<div class=" col-md-6">
<div class="form-group">
<label class="label-block">Prezime</label>
<input name="lastName" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block">Telefon</label>
<input name="number" type="digits" required class="texbox">
</div>
</div>
JS :
<script src="scripts/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function () {
$("#configuration-form").validate({
messages: {
name: {
required: "Error!"
}
}
});
});
</script>
<script>
$("#commentForm").validate();
</script>
That is my code in html and css... I managed to make my textbox turns red when the email is not ok. how to create that popup text.
It looks like you are using Twitter Bootstrap, and they have a popover feature or alert message that you can use: Bootstrap - popovers
HTML :-
Validation for Email.
<input type="text" id="email">
<input type="submit" onclick="validateEmail()" >
JavaScript Code :-
function validateEmail() {
var emailText = document.getElementById('email').value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText)) {
return true;
} else {
alert('Bad email address: ' + emailText);
document.getElementById("email").style.backgroundColor = "Red";
return false;
}
}
Working Demo for Email Validation.
I hope it will help you.
I have a web form that submits if my function validate form returns true in that function i wrote an if statement that if another function called usernamecheck returns true then return the validateform function true. I dont want the form to submit unless you click the button to check the username. I know i didnt write this the best way i hope you understand
<!-- Signup Form -->
<form name='signup' action="subscription.php" onsubmit="return validateForm();" method="post" >
<input type="text" id="signupUsername" name="signupusername" placeholder="Business Name" tabindex=1 required>
<input type="password" id="signupPassword" placeholder="Password" name="signuppassword" tabindex=2 required> <br>
<input type="text" id="ownerName" placeholder="Owner's Name" name="ownername" tabindex=3 required>
<input type="email" id="signupEmail" placeholder="Email" name="signupemail" tabindex=4 required>
<input type="tel" id="signupphoneNumber" placeholder="Phone Number" name="signupphonenumber" tabindex=5 required>
<input type="image" id="signupSubmit" src="images/signupBtn.jpg">
<input type="text" id="city" placeholder="City" name="city" tabindex=6>
<input type="text" id="state" placeholder="State" name="state" tabindex=7>
This is the button that you click to check your username if it exists
<input type="button" id='check' value="Check It">
//
</form>
<script type="text/javascript">
Below there is the function where if you click the button above it checks the function usernamecheck
$(function() {
$( "#check" ).click(function() {
return usernamecheck();
});
});
Below is the validateForm function where if usernamecheck returns true it returns true as well and submits the form
function validateForm()
{
if(usernamecheck() && $("#signupUsername").val().length < 4) {
return true;
}
}
function usernamecheck() {
$.post( "checkusername.php", { username: $("#signupUsername").val() })
.done(function( data ) {
result = JSON.parse(data);
if(result["status"]== "Username is taken")
{
alert("username is taken");
return false;
}
else if(result["status"]== "Username is Available") {
alert("username is Available");
return true;
}
else {
alert('You did not check the username');
}
});
}
</script>
<!-- Map Logo -->
<img src='images/map.jpg' id="map" class='menuitems'>
<!-- About Us Logo -->
<img src='images/aboutus.jpg' id="aboutus" class='menuitems'>
<!-- People Logo -->
<img src='images/people.jpg' id="people" class='menuitems'>
</div>
</div>
</div>
</body>
</html>
I am looking to make a simple form validation error message that displays under the username field.
I cannot seem to figure it out.
<form name ="myform" onsubmit="validation()">
Username: <input type ="text" name="username" /><br />
<input type ="submit" value="submit" />
<div id ="errors">
</div>
</form>
Here is my validation script:
function validation(){
if(document.myform.username.value == ""){ //checking if the form is empty
document.getElementById('errors').innerHTML="*Please enter a username*";
//displaying a message if the form is empty
}
You need to stop the submission if an error occured:
HTML
<form name ="myform" onsubmit="return validation();">
JS
if (document.myform.username.value == "") {
document.getElementById('errors').innerHTML="*Please enter a username*";
return false;
}
JavaScript
<script language="javascript">
var flag=0;
function username()
{
user=loginform.username.value;
if(user=="")
{
document.getElementById("error0").innerHTML="Enter UserID";
flag=1;
}
}
function password()
{
pass=loginform.password.value;
if(pass=="")
{
document.getElementById("error1").innerHTML="Enter password";
flag=1;
}
}
function check(form)
{
flag=0;
username();
password();
if(flag==1)
return false;
else
return true;
}
</script>
HTML
<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">
<div id="error0"></div>
<input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
controls">
<div id="error1"></div>
<input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">
<button type="submit" class="btn">Sign in</button>
</div>
</div>
</form>
I would strongly suggest you start using jQuery. Your code would look like:
$(function() {
$('form[name="myform"]').submit(function(e) {
var username = $('form[name="myform"] input[name="username"]').val();
if ( username == '') {
e.preventDefault();
$('#errors').text('*Please enter a username*');
}
});
});