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.
Related
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 am developing a web directory with a form on one of its pages. JS validation plug in is used. While submitting the form without filling any Input fields, the form throws errors below each input field as expected! But submitting the form with just one input box filled in refreshes the current page as the action value is set to current page with PHP codes in it, instead of staying on the same page to continue to throw errors for the rest of the fields that are yet to be filled in! I have searched online to find nothing useful in figuring out what is wrong with the script. Could anyone here please look into the code below and recommend the best solution? Thanks.
$(document).ready(function() {
$("#userForm").validate({
rules: {
cname: {
required: true,
lettersonly: true,
minlength: 3
},
cemail: {
required: true,
email: true
},
cphone: {
required: true,
number: true,
minlength: 10,
maxlength: 10
},
cbusiness: {
required: true,
url: true
},
cbcategory: {
required: true,
minlength: 6
},
curl: {
required: true,
minlength: 6
},
},
messages: {
cname: "Please enter your name",
cemail: "Please enter a valid email address",
cphone: {
required: "Please enter your phone number",
number: "Please enter only numeric value"
},
cbusiness: {
required: "Please enter your business",
},
cbcategory: {
required: "Please enter a business category",
},
curl: {
required: "Please enter the URL to your website",
},
}
});
});
The form is as below.
<form action="" method="post" name="userForm" id="userForm">
<input type="text" name="cname" id="cname" placeholder=" Your Name">
<input type="text" name="cemail" id="cemail" class="email" placeholder="Your Email">
<input type="text" name="cphone" id="cphone" placeholder="Your Phone">
<input type="text" name="cbusiness" id="cbusiness" class="email" placeholder=" Your Business">
<input type="text" name="cbcategory" id="cbcategory" placeholder="Business category">
<input type="text" name="curl" id="curl" class="email" placeholder="URL"><br>
<label for='message'>Enter the code in the box below : </label>
<img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'>
<input type="text" id="captcha_code" name="captcha_code">
<input type="submit" name="Submit" id="Submit" value="Submit" class="button1"><br>
Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.
</form>
Assuming you have included the validation libraries corectly, you will have to set messages for all of the validation types like:
messages: {
cname: {
required: "Please enter your name",
lettersonly: "Letters only",
minlength: "Min length 3 required"
},
cemail: {
required: "Please enter a valid email address",
email: "Invalid email"
}
}
Working JSFIDDLE.
You have to include the plugin files something like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
UPDATE:
After discussing with OP on chat, we came to the conclusion that the plugin files had to be included correctly and there was an incompatibility between the jQuery version(v 1.7.1) he used and the plugin version(v 1.16.0). So we had to add a custom method for lettersonly.
The code for custom method:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
I'm facing some problems with jQuery Validate. I've already put the rules but when i'm submitting the form, nothing happens.
I'm using ASP.NET MVC 4 and Visual Studio 2010.
EDIT: Click here to see my entire code. I'm trying to post it here but i'm getting the following error: 403 Forbidden: IPS signature match. Below is part of my code with Andrei Dvoynos's suggestion. I'm getting the same error. Clicking on submit and the page being reloaded
#{
ViewBag.Title = "Index";
}
#section Teste1{
<script type="text/javascript">
$(document).ready(function () {
$("#moeda").maskMoney();
$("#percent").maskMoney();
$(":input").inputmask();
$('#tel').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.inputmask({ "mask": "(99) 99999-999[9]" });
} else {
element.inputmask({ "mask": "(99) 9999-9999[9]" });
}
}).trigger('focusout');
//the code suggested by Andrei Dvoynos, i've tried but it's occurring the same.
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});
});
</script>
}
#using (#Html.BeginForm("", "", FormMethod.Post,
new { id = "form1", name = "form1" }))
{
<fieldset>
<legend>Sign In</legend>
<div class="form-group" id="divCpf">
<label for="cpf">CPF</label>
<input data-inputmask="'mask': '999.999.999-99'" class="form-control" id="cpf" />
</div>
<div class="form-group" id="divCep">
<label for="cep">CEP</label>
<input data-inputmask="'mask' : '99999-999'" type="text" class="form-control" id="cep" placeholder="CEP" />
</div>
<div class="form-group" id="divTel">
<label for="tel">Telefone</label>
<input type="text" class="form-control" id="tel" placeholder="tel" />
</div>
<div class="form-group" id="email">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Email" />
</div>
<div class="form-group" id="divcnpj">
<label for="cnpj">CNPJ</label>
<input data-inputmask="'mask' : '99.999.999/9999-99'" type="text" class="form-control" id="cnpj" placeholder="CNPJ" />
</div>
<div class="form-group">
<label for="moeda">Moeda</label>
<input type="text" id="moeda" data-allow-zero="true" class="form-control" />
</div>
<div class="form-group">
<label for="Percent">Percent</label>
<input type="text" id="percent" data-suffix="%" data-allow-zero="true" class="form-control" maxlength="7" />
</div>
<input type="submit" class="btn btn-default" value="Sign In" id="sign" />
</fieldset>
}
My tests (all unsuccessful):
1 - put the $("form").validate() into $(document).ready()
2 - put the required class on the fields.
jQuery Validate plugin version: 1.13.0
In addition to the fatal problem you fixed thanks to #Andrei, you also have one more fatal flaw. The name attribute is missing from your inputs.
Every element must contain a unique name attribute. This is a requirement of the plugin because it's how it keeps track of every input.
The name is the target for declaring rules inside of the rules option.
$("#form1").validate({
rules: { // <- all rule declarations must be contained within 'rules' option
cpf: { // <- this is the NAME attribute
required: true,
....
DEMO: http://jsfiddle.net/3tLzh/
You're missing the rules property when calling the validate function, try something like this:
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});
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>
I am using jquery for form validation. Rest is well except the confirm password field. Even when the same password is typed, the Please enter the same password. is not removed.
My script is:
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
password: {
required: true, minlength: 5
},
c_password: {
required: true, equalTo: "#password", minlength: 5
},
email: {
required: true, email: true
},
phone: {
required: true, number: true, minlength: 7
},
url: {
url: true
},
description: {
required: true
},
gender: {
required: true
}
},
messages: {
description: "Please enter a short description.",
gender: "Please select your gender."
}
});
});
-->
</script>
And inside the form tag:
<div class="form-row"><span class="label">Password</span><input type="password" name="password" class="required" id="password" /></div>
<div class="form-row"><span class="label">Confirm Password</span><input type="password" name="c_password" id="c_password" /></div>
Any suggestion?
Would be much thankful for the help.
Your fields doesn't have the ID property.
In jQuery the "#password" selector means "the object that has an id property with value 'password'"
Your code should look like this:
<input type="password" name="password" id="password" class="required"/>
<input type="password" id="password" class="nomal required error" value="" name="cpassword">
<input type="password" equalto="#password" class="nomal required error" value="" name="cpassword">
Be sure that your password's input text has id 'password'
rules: {
isn't closed. Put another } after:
messages: {
description: "Please enter a short description.",
gender: "Please select yor gender."
}
This is as well as the answer about the element ID's.
Be sure that no other input with tag id='password' in that same page.
I came across some issues when using camelCase id's for the password inputs. I finnally got it working with different 'name' and 'id'.
<input type="password" id="pass" placeholder="New password" name="newPassword">
<input type="password" id="pass2" placeholder="New password" name="repeatNewPassword">
<input type="email" id="inputNewEmail" name="newEmail" placeholder="New email">
<input type="email" id="repeatNewEmail" name="repeatNewEmail" placeholder="New email>
Then in the JS:
rules: {
newPassword: {
minlength: 6
},
repeatNewPassword: {
minlength: 6,
equalTo: "#pass"
},
newEmail: { email: true},
repeatNewEmail: {email: true, equalTo: '#inputNewEmail'},
}
So refer to the input field by its 'name' but define equalTo deppendency using 'id'. I'm not sure about the camelCase issue, for the email inputs it worked, but exactly same nomenclature with password inputs didn't work, according to my experience
if($("#newpassword").val()!== ($("#conformpassword").val())){
$('#newpasswordId').html('<font color="red">Your password does not match</font>');
$("#newpassword").val('');
$("#conformpassword").val('');
$('#newpassword').css("border", "#FF0000 solid 1px")
$('#conformpassword').css("border", "#FF0000 solid 1px")
$("#newpassword").focus();
return false;
}