Jquery Validation on cloned elements - javascript

I am using the following JQuery validation:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I have the following element:
<div class="form-item">
<label for="Reference_name" class="required">Name: <span class="required">*</span></label>
<input name="Reference[name][]" class="form-input validate {validate:{required:true,minLength:2,messages:{required:'Your name is required',minLength:'Your name is too short'}}}" id="Reference_name" type="text">
</div>
I have cloned the element but the validation is only appearing on the first element. I would like it to validate against the second too and show the error message label.
Can someone help with this please.

elements must be unique
<label for="Reference_name" class="required">Name:<span class="required">*</span></label>
<input type="text" id="Reference_name" name="Reference[Name]" id="Reference_name" required="required" maxlength="255" />
File Js
$(document).ready(function() {
validate_form();
});
function validate_form() {
$("#id_of_your_form").validate({
rules: {
'Reference_name': {
required:true,
minlength: 2,
}
},
},
messages: {
'Reference_name': {
required:"Your name is required",
minLength:'Your name is too short'
},
}
});
}
if you want to compare two fields
http://docs.jquery.com/Plugins/Validation/Methods/equalTo#other

Put your validation function in a global variable like this:
var validate_form_function = function(){
if($(".app-form").length > 0){
$('.app-form').validate({
rules: {
comment_message: {
required: true,
minlength: 2
}
},
messages: {
comment_message: {
required: "Your message",
minlength: "Your message"
}
}
});
}
};
Then revalidate your cloned form with the function like this :
validate_form_function();

Related

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 Validation - Add custom callback function, check if a string has a space doesn't working

This is my code, checkUsername function doesn't working, how should I fixit?
<form id="register_form" method="post" action="">
<fieldset>
<legend>Info</legend>
<div>
<label>Username</label>
<input type="text" name="username" id="username"/>
<input type="submit" id="btnAccess" class="button" value="Submit" name="btnAccess"/>
</fieldset>
</form>
$(document).ready(function() {
var validator = $('#register_form').validate({
rules: {
username: {
required: true,
minlength: 4,
checkUsername: true
}
},
messages: {
username: {
required: "No blank",
minlength: "Enter atleast 4 words"
}
}
});
$.validator.addMethod('checkUsername', function(value, element) {
return /\s/g.test(value);
}, "error");
});
http://jsfiddle.net/nambatre/rEpqr/
P/S: if I want to check a string has some words as #, # etc, what should I do?
You need to return true is the the value is true
it should be
$.validator.addMethod('checkUsername', function(value, element) {
return this.optional(element) || !/\s/g.test(value);
}, "error");
Demo: Fiddle

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

jQuery Validate Plugin - How to create a simple custom rule?

How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?
For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?
You can create a simple rule by doing something like this:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
And then applying this like so:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
Just change the contents of the 'addMethod' to validate your checkboxes.
$(document).ready(function(){
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "http://"+location.host+"/checkUser.php",
data: "checkUsername="+value,
dataType:"html",
success: function(msg)
{
//If username exists, set response to true
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"Username is Already Taken"
);
$("#regFormPart1").validate({
username: {
required: true,
minlength: 8,
uniqueUserName: true
},
messages: {
username: {
required: "Username is required",
minlength: "Username must be at least 8 characters",
uniqueUserName: "This Username is taken already"
}
}
});
});
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
return jQuery.validator.methods['date'].call(
this,value,element
)||value==("0000/00/00");
}, "Please enter a valid date."
);
// connect it to a css class
jQuery.validator.addClassRules({
optdate : { optdate : true }
});
Custom Rule and data attribute
You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true";
So to check if at least one of a group of checkboxes is checked:
data-rule-oneormorechecked
<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" />
addMethod
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
And you can also override the message of a rule (ie: Atleast 1 must be selected) by using the syntax data-msg-rulename="my new message".
NOTE
If you use the data-rule-rulename method then you will need to make sure the rule name is all lowercase. This is because the jQuery validation function dataRules applies .toLowerCase() to compare and the HTML5 spec does not allow uppercase.
Working Example
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
$('.validate').validate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<form class="validate">
red<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" data-msg-oneormorechecked="Check one or more!" /><br/>
blue<input type="checkbox" name="colours[]" value="blue" /><br/>
green<input type="checkbox" name="colours[]" value="green" /><br/>
<input type="submit" value="submit"/>
</form>
Thanks, it worked!
Here's the final code:
$.validator.addMethod("greaterThanZero", function(value, element) {
var the_list_array = $("#some_form .super_item:checked");
return the_list_array.length > 0;
}, "* Please check at least one check box");
You can add a custom rule like this:
$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);
And add it as a rule like this:
PhoneToggle: {
booleanRequired: 'on'
}
For this case: user signup form, user must choose a username that is not taken.
This means we have to create a customized validation rule, which will send async http request with remote server.
create a input element in your html:
<input name="user_name" type="text" >
declare your form validation rules:
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
the remote code should be like:
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
Step 1 Included the cdn like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Step 2 Code Like
$(document).ready(function(){
$("#submit").click(function () {
$('#myform').validate({ // initialize the plugin
rules: {
id: {
required: true,
email: true
},
password: {
required: true,
minlength: 1
}
},
messages: {
id: {
required: "Enter Email Id"
},
password: {
required: "Enter Email Password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}):
});

Categories

Resources