Hello guys I'm doing a login form with jquery validation which checks if the user id and password are valid.
This is what I've tried so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script language="javascript">
$(document).ready(function(){
$("#loginForm").validate({
rules: {
username: "required",
password: {
required: true
}
},
messages: {
username: "This field is required",
password: {
required: "This field is required"
}
}
});
$("#loginForm").submit(function(){
$("#report").removeClass().addClass('loader').html('<img src="img/login/spinner.gif">').fadeIn(1000);
$.post("checklogin.php",{ username:$('#username').val(),password:$('#password').val()},function(data){
if(data=='yes'){
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/spinner.gif">').addClass('log').fadeTo(900,1,function(){
document.location='processed.php';
});
});
}
else {
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
});
</script>
What I want to happen is, if fields have empty values then it should validate and display fields are required. But my form displays the error message and goes to check as if the fields have values. Why is that happening? Any ideas to resolve this issue? Thanks.
UPDATE: index.html
<form class="form-signin" action="checklogin.php" method="post" id="loginForm">
<img alt="" src="img/irasa_logoa.png" title="IRASA">
<h2 class="form-signin-heading">Log In</h2>
<input type="text" class="input-block-level" placeholder="User ID" name="username" id="username" class="required">
<input type="password" class="input-block-level" placeholder="Password" name="password" id="password" class="required">
<button class="btn btn-large btn-custom" type="submit">Log in</button>
<div id="report"></div>
</form>
</div> <!-- /container -->
Try this
$("#loginForm").validate({
rules: {
username: "required",
password: "required"
},
messages: {
username: "This field is required",
password: "This field is required"
},
submitHandler: function(form) {
$("#report").removeClass().addClass('loader').html('<img src="img/login/spinner.gif">').fadeIn(1000);
$.post("checklogin.php",{ username:$('#username').val(),password:$('#password').val()},function(data){
if(data=='yes'){
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/spinner.gif">').addClass('log').fadeTo(900,1,function(){
document.location='processed.php';
});
});
} else {
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
})
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
}
});
I think it is as simple as adding a "required" class in your input type. just add class="required".
This will work as you're using jquery.validate.min.js.
Refer: http://help.campaignmonitor.com/topic.aspx?t=194
If you are using jQuery validate then you should not also bind to the submit event for the form yourself. Put that code in a submitHandler instead. See http://jqueryvalidation.org/validate#submithandler
Edit to add example.
Note that I have not checked that your function (which you had as a submit event) is right - just copied it. I have also removed the rules since as #Sambhav Sharma said, you should simply add a "required" class to the fields and it is automatically required). I also assume the submit on blur should be triggered always, not after the validation submit. I have not tested any of this :)
$(document).ready(function(){
$("#loginForm").validate({
messages: {
username: "This field is required",
password: {
required: "This field is required"
}
},
submitHandler: function(){
$("#report").removeClass().addClass('loader').html('<img src="img/login/spinner.gif">').fadeIn(1000);
$.post("checklogin.php",{ username:$('#username').val(),password:$('#password').val()},function(data){
if(data=='yes'){
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/spinner.gif">').addClass('log').fadeTo(900,1,function(){
document.location='processed.php';
});
});
} else {
$("#report").fadeTo(200,1,function(){
$(this).html('<img src="img/login/icon_error.gif"> Username or password error.').addClass('error').fadeTo(900,1);
});
}
});
return false;
})
});
$("#password").blur(function(){
$("#login_form").trigger('submit');
});
});
Related
im new to jquery validator, im trying to use regex to check if numbers, capital and special characters are included. I have the following html
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row white-bg spacepad">
<div id="keypass">
<form method="POST" class="form-horizontal" id="keyform" name="keypasser">
<div class="form-group"><label class="col-sm-2 control-label">Decryption Key For EPins</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypassx" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Confirm Decryption Key</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypass2" /></div>
</div>
<input type="submit" class="btn btn-primary btn-rounded btn-block" value="Submit" />
</form>
</div>
</div>
and the following jquery, when i remove the addmethod it works, please what am i doing wrong
<script type="text/javascript">
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='keypasser']").validate({
// Specify validation rules
rules: {
keypassx: {
required: true,
minlength: 8,
passchecker: true,
},
keypass2: {
required: true,
equalTo: "#keypassx",
}
},
// Specify validation error messages
messages: {
keypassx: {
required: "Epins password required",
minlength: "Minimum length allowed is 8 characters",
passchecker: "Password should contain numbers, special characters and one uppercase",
},
keypass2: {
required: "Confirmation password requied",
equalTo: "Password does not match Epins Password",
}
},
$.validator.addMethod("passchecker",
function(value, element) {
return /^[A-Za-z0-9\d=!\-#._*]*$/.test(value);
});
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
</script>
kindly help out
Please try to use regular expression as
var patt = new RegExp("e");
var res = patt.test(str);
You directly use the regular expression. Please create object and try it.
The addMethod function accepts three params check the docs:
$.validator.addMethod("passchecker",
function(value, element) {
if(/^[A-Za-z0-9\d=!\-#._*]*$/.test(value)) {
return true;
} else {
return false;
}
}, "Your validation message goes here");
I am trying basic client-side form validation using jQuery validation plugin.I have a basic sign up form, if I click on a button to create an account with all fields empty(just for testing), I am getting nice error messages as expected on all form fields except for only one field for inputting cellphone number. I have downloaded the code from the internet and this is the only field I have added.I am using Xampp, Things became even more strange after I moved all files to another computer and try to test the same validation, Guess what? it's no longer working as expected for all fields. This problem has been frying my brains, any help I will be grateful below is the code
HTML
<h2 class="form-signin-heading">Sign Up</h2><hr />
<div id="error">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="user_name" id="user_name" />
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name="user_email" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Cellphone" name="user_cellphone" id="user_cellphone" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Retype Password" name="cpassword" id="cpassword" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="btn-save" id="btn-submit">
<span class="glyphicon glyphicon-log-in"></span> Create Account
</button>
</div>
</form>
JS
$('document').ready(function()
{
/* validation */
$("#register-form").validate({
rules:
{
user_name: {
required: true,
minlength: 3
},
user_cellphone: {
required: true,
number: true
},
password: {
required: true,
minlength: 8,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
user_email: {
required: true,
email: true
}
},
messages:
{
user_name: "Enter a Valid Username",
user_cellphone:{
required: "Provide a phone number",
number: "Phone Needs To Be a number"
},
password:{
required: "Provide a Password",
minlength: "Password Needs To Be Minimum of 8 Characters"
},
user_email: "Enter a Valid Email",
cpassword:{
required: "Retype Your Password",
equalTo: "Password Mismatch! Retype"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#register-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
else if(data=="registered")
{
$("#btn-submit").html('Signing Up');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".signin-form").load("successreg.php"); }); ',5000);
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
/* form submit */
Below is a snapshot of the form, I cant really figure out where is the problem.
You're declaring the number rule, but your corresponding message is assigned to the minlength rule...
rules: {
user_cellphone: {
required: true,
number: true
},
....
},
messages: {
user_cellphone: {
required: "Provide a phone number",
minlength: "Phone Needs To Be a number"
},
....
And document should not be in quotes...
$(document).ready(function() {...
Working DEMO: http://jsfiddle.net/bh5g0wfe/
Side note: You may want to read this too...
Dangerous implications of Allman style in JavaScript
I'm using jquery validation plugin to validate a form. It is working if all fields are left blank. But if I entered a file in the input field and leave blank the other required fields it doesn't validate the other elements anymore it just submit the form to the server.
<script>
$().ready(function() {
$("#form1").validate({
submitHandler: function (form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
jAlert(response);
});
return false;
},
ignore: [],
rules: {
title: { required: true, minlength: 2, maxlength: 25 },
text1: {
required: function() {
CKEDITOR.instances.text1.updateElement();
}
},
text2: {
required: function() {
CKEDITOR.instances.text2.updateElement();
}
},
newsimage: {
required: true,
accept: "image/*"
},
},
messages: {
title: {
required: "Please enter the Title",
minlength: "Title must consist of at least 2 characters"
},
text1: {
required: "Please enter text",
minlength: "Must consist of at least 2 characters"
},
text2: {
required: "Please enter text",
minlength: "Must consist of at least 2 characters"
}
}
});
});
</script>
Here's the form
<form id="Form1" enctype="multipart/form-data" method="post" action="save.php" >
Title: <input name="title" size="40" maxlength="255">
<br>
<label for="newsimage">News Image</label>
<input type="file" id="newsimage" name="newsimage">
<br> News Summary:
<textarea id="text1" name="text1" rows="7" cols="30"></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'text1' );
</script>
<br> News Full Story:
<textarea id="text2" name="text2" rows="7" cols="30"></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'text2' );
</script>
<br> <input type="submit" name="submit" value="Add News">
You could use required on your form tags like this :
<input name="title" size="40" maxlength="255" required>
that should force some input. ( it is not sanitized )
It wasn't working on my end because I was missing additional-methods.js, so adding it solve the problem.
<script src="js/additional-methods.min.js"></script>
Try this user friendly validation plugin
https://github.com/vanarajcs/jquery-form-validation
in order to activate any jquery validation library first of all you need to define that library below jquery cdn. your structure should be like this:
<!-- define jquery file -->
<!-- Now define jquery validation library -->
for a safer side define you jquery file on header and your validation library after main code.
<script src="jquery.js"></script>
<script src="jquery.validate.js"></script>
<script>
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$().ready(function() {
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "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"
},
}
});
});
</script>
</head>
<body>
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>Validating a complete form</legend>
<p>
<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" type="text" />
</p>
<p>
<label for="lastname">Lastname</label>
<input id="lastname" name="lastname" type="text" />
</p>
<input class="submit" type="submit" value="Submit"/>
</body>
Trailing commas (,) are illegal in JavaScript. When you do something like this:
rules: {
firstname: 'required',
lastname: 'required',
}
the JavaScript engine will think that }, is the next item in the rules object.
You need to do something like this:
rules: {
firstname: 'required',
lastname: 'required' // <-- no comma at end
}
I am trying to implement the simple form validation plugin found here: http://www.jquery4u.com/forms/basic-jquery-form-validation-tutorial/
but I cannot seem to get it working.
I have a simple form:
<form id="signupform" name="signupform" action="page" method="post" novalidate="novalidate">
<input type="text" id="signupusername" name="signupusername">
<input type="text" id="signupemail" name="signupemail">
<input type="password" id="signuppassword" name="signuppassword">
<input type="text" id="signupfirstname" name="signupfirstname">
<input type="text" id="signuplastname" name="signuplastname">
<input type="checkbox" name="tandc" value="tandcyes"> I agree
<button type="submit" value="Signup" class="submit">Signup</button>
</form>
And the associated plugin script:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#signupform").validate({
rules: {
signupusername: "required",
signupfirstname: "required",
signuplastname: "required",
signupemail: {
required: true,
email: true
},
signuppassword: {
required: true,
minlength: 5
},
tandcyes: "required"
},
messages: {
signupusername: "Please enter your User Name",
signupfirstname: "Please enter your firstname",
signuplastname: "Please enter your lastname",
signuppassword: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
signupemail: "Please enter a valid email address",
tandcyes: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
But it will just not work.
Of course I have checked both the plugin and link to JQuery are present and correct. Nothing appears in the console either. It just doesnt seem to trigger.
Does anyone know whats going on?
Thanks!
The problem is that you have included 2 times the same script.
The functions in script with validation appear 2 times in the source. Which is rather hard for the browser to know which one to pick.
Check head for two scripts.
Please add all your inputs in the form they are not present in the form tags.
<form>
<input type=... />
<input type=... />
</form>
if you close the form before your inputs that is the problem.
use this page and its works
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<title>Basic jQuery Validation Form Demo | jQuery4u</title>
<link rel="stylesheet" type="text/css" href="bootstrap.css">
<script type="text/javascript">
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#signupform").validate({
rules: {
signupusername: "required",
signupfirstname: "required",
signuplastname: "required",
signupemail: {
required: true,
email: true
},
signuppassword: {
required: true,
minlength: 5
},
tandcyes: "required"
},
messages: {
signupusername: "Please enter your User Name",
signupfirstname: "Please enter your firstname",
signuplastname: "Please enter your lastname",
signuppassword: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
signupemail: "Please enter a valid email address",
tandcyes: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
</head>
<body>
<h1>Basic jQuery Validation Form Demo</h1>
<!-- HTML form for validation demo -->
<form id="signupform" name="signupform" action="page" method="post" novalidate="novalidate">
<input type="text" id="signupusername" name="signupusername">
<input type="text" id="signupemail" name="signupemail">
<input type="password" id="signuppassword" name="signuppassword">
<input type="text" id="signupfirstname" name="signupfirstname">
<input type="text" id="signuplastname" name="signuplastname">
<input type="checkbox" name="tandc" value="tandcyes"> I agree
<button type="submit" value="Signup" class="submit">Signup</button>
</form>
<!-- END HTML form for validation -->
</body>
</html>