override jquery validation message - javascript

I'm trying to override the default message in jquery validation message I did as the documentation told but no use it is still show "This field is required." ?
http://jsfiddle.net/7Yrz7/
$(function () {
$('form').validate({
rules: {
email:"required",
password:"required",
messages: {
email: "Please enter an email address.",
password: "This field is required."
}
}
});
});

It should be:
$("form").validate({
rules: {
email: "required",
password: "required"
}, // <-- here
messages: {
email: "Please enter an email address.",
password: "This field is required."
}
});
You need to close the rules before using messages here.
Updated Fiddle

For using Validate plugin you have to add Rule first and then message.
The Scripts
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}, // end of rules
messages: {
field1: "You cannot leave field1 blank",
field2: "You cannot leave field1 blank"
}// end of message
});
});
The HTML
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

Related

Getting error when trying to do the customized message in jQuery validate

I have been trying many times with JQuery for validating errors using customized messages, but I am still confused that where I am making the mistake.I have tried with the normal validating messages, but when I tried with the customized, it shows me an error.
Below is the sample code which i have tried so far and unsucessful in executing it.
<form id="myform">
<tr>
<td class="alpha">username</td>
<td>
<input type="username" type="text" value="">
</td>
</tr>
<br/>
<tr>
<td class="alpha">postcode</td>
<td>
<input type="postcode" type="text" value="">
</td>
</tr>
<input type="submit" />
</form>
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$document.ready(function() {
$("#myform").validate({
rules: {
password: "required",
postcode: {
required: true,
minlength: 3
}
},
messages: {
username: {
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: {
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
});
});
As written, your code would not work with the default messages either.
Please read my comments in the code...
rules: {
password: "required", // <- input with name="password" (where is "password"?)
postcode: { // <- input with name="postcode"
required: true,
minlength: 3
}
},
messages: {
username: { // <- input with name="username"
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: { // <- input with name="postcode"
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
The rules and messages objects' parameters are keyed by the name attribute of the input element. Your input elements do not contain any name attributes. The plugin mandates that all form inputs contain a unique name, and the plugin will not work without these.
You have invalid values for the type attribute. There are no such things as type="username" and type="postcode"; and you erroneously have more than one type attributes on each input, <input type="username" type="text" value="">
In your case, you don't even attempt to define any rules for a username field. You only have password and postcode within the rules object.
Fix your invalid HTML markup and JavaScript...
Remove all extraneous type attributes from each input.
Add a unique name attribute to each input.
Only reference your name attributes within rules and messages objects.
DEMO: jsfiddle.net/2tx6u7wf/

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

How to validate input fields with a dot in name using the jquery validation plugin?

I'm using this jquery validation plugin
<s:textfield cssClass="form-control input-default" name="contest.title" id="title" placeholder="Enter Title"
/>
Validation doesn't work for this, but if I change the name to title - validation works.
I tried searching, but couldn't find a means to validate fields with a . in their name.
Please help
Update
Script
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#contestform").validate({
submitHandler: function(form) {
// return false; // block the default submit action
},
rules: {
title: {
required: true
},
link: {
required: true
},
startdt: {
required: true
},
enddt: {
required: true
},
descr: {
required: true
},
},
messages: {
title: "Please enter a title",
link: "Please enter the sponser redirection link",
startdt: "Please select start date",
enddt: "Please select end date",
descr: "Please enter description"
}
});
});
</script>
Part of the form
<form action="" enctype="multipart/form-data" method="post" id="contestform">
<s:hidden name="option" value="option"/>
<s:hidden name="contest.idcontest"/>
<div class="form-group">
<label for="title">Title</label>
<s:textfield cssClass="form-control input-default" name="contest.title" id="title" placeholder="Enter Title"
/>
</div>
You need to put the field names in qoutes. From the plugin documentation
Fields with complex names (brackets, dots)
When you have a name attribute like user[name], make sure to put the
name in quotes. More details in the General Guidelines.
The sample in the linked reference:
$("#myform").validate({
rules: {
// no quoting necessary
name: "required",
// quoting necessary!
"user[email]": "email",
// dots need quoting, too!
"user.address.street": "required"
}
});

jQuery - Validate Password

I am trying to use jQuery to validate my two password fields with each other.
My code looks like this:
jQuery('#settingsForm').validate(
rules : {
npassword : {
},
pass_check : {
equalTo : '#npassword'
}
}
});
This is the HTML for the input fields:
<label for='npassword'>New Password</label>
<input type='password' class='span10 password_check' name='npassword' id='npassword' value='' placeholder='New Password'>
<div class='separator'></div>
<label for='pass_check'>Confirm New Password</label>
<input type='password' class='span10' name='pass_check' id='pass_check' value='' placeholder='Confirm New Password'>
<div class='separator'></div>
Although this doesn't do anything. What should I change? I am new to jQuery and Javascript in general.
Thanks in advance.
You should fill out the configuration for npassword, e.g. by using required: true. See here: http://jsfiddle.net/JtTgM/
1) You are missing an opening brace, {, right after .validate(:
jQuery('#settingsForm').validate({ // <-- opening brace { was missing
2) Maybe you want to specify the required rule for the first password field. Otherwise, when both fields are blank, they both match and the form is valid.
npassword: {
required: true
},
3) You can override the default messages with the messages option:
jQuery('#settingsForm').validate({
rules: {
npassword: {
required: true
},
pass_check: {
equalTo: '#npassword'
}
},
messages: {
npassword: {
required: "this field is required"
},
pass_check: {
equalTo: "the passwords must match"
}
}
});
Working DEMO: http://jsfiddle.net/vsLWg/
$( "#Form").validate({
rules: {
old_password: "required",
password: "required",
new_password: {
equalTo: "#password"
}
}
});

jQuery Validate: Retaining error after validation

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

Categories

Resources