https://codepen.io/joshuajazleung/pen/jGEyNa
<form data-parsley-validate>
<input type="file" name="files" multiple data-parsley-max-files="4">
<button type="submit">submit</button>
</form>
window.Parsley
.addValidator('maxFiles', {
requirementType: 'integer',
validateNumber: function(value, requirement) {
return true;
},
messages: {
en: 'Maximum number of files is 4.',
}
});
The file input is supposed to be invalid all the time because the validator return true (for testing purposes). But when I clicked submit button, the input isn't valid. I am wondering why??
It's because the value of you input is not a valid number (ever) and you only defined validateNumber. You need to define a validateString.
To validate files, inspire yourself from the custom validators example
Related
I’m trying to validate a PromoCode prior to form submission. I AM able to do that but if the result is false, I am unable to submit the form unless the input field has been cleared. I’m a self-taught hobby coder and don’t really understand JS, AJAX or cfcomponent (this is my first shot at all of it.) I’ve had a great deal of help getting to this point. All additional help is greatly appreciated.
SUMMARY:
If the PromoCode the user types into the text field matches what’s stored in the DB… all is good. They submit the form and get the discount.
If the PromoCode the user types into the text field does NOT match, they get the message “Sorry, that is not a valid promo code” but cannot submit the form unless the text field has been cleared.
I need the user to be able to submit the form if the PromoCode is invalid… they just wouldn’t get the discount. We just told them it was invalid so they’re on their own. I'd hate to have the user not understand this and leave the site frustrated without registering.
JAVASCRIPT
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
promocode: {
remote: {
url: "/components/promoCodeComponent.cfc?method=validatePromoCode",
data: {
courseId : $("#courseId").val()
}
}
}
},
messages: {
promocode: {
remote: jQuery.validator.format("Sorry, {0} is not a valid Promo Code")
}
},
errorClass: "text-danger",
validClass: "text-success"
});
});
FORM
<form id="signupform" autocomplete="off" method="get" action="">
<!--- demo only --->
Course Id: <input id="courseId" name="courseId" type="text" value=""><br>
Promo Code: <input id="promocode" name="promocode" type="text" value=""><br>
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</form>
CFC
component {
// Note: See Application.cfc docs on setting application level datasource, i.e. "this.datasource"
remote boolean function validatePromoCode(string courseId, string promoCode) returnFormat="json"{
local.qPromoCode = queryExecute(
" SELECT COUNT(*) AS TotalFound
FROM Courses
WHERE Id = :courseId
AND PromoCode = :promoCode
AND LEN(PromoCode) > 0
"
, {
promoCode = { value=arguments.promoCode, cfsqltype="varchar" }
, courseId = { value=arguments.courseId, cfsqltype="integer", null=!isNumeric(arguments.courseId) }
}
, { datasource=“My_DataSource_Name" }
);
;
if (local.qPromoCode.TotalFound gt 0) {
return true;
}
return false;
}
}
I am using jquery validation plug-in to validate my forms.
https://jqueryvalidation.org/
When I call .valid() method of some element in another element validation then the current element error message is not getting removed.
Say I have elements E1 and E2 . The validation method for element E1 is Method1.
In Method1 , if I call E2.valid() to programattically trigger validation.
The error message in E1 is not getting removed even thought the element is valid.
Please find the code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate IP Address using jQuery</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</script>
<script type="text/javascript" src=
"http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</script>
<script type="text/javascript">
$(document).ready((function() {
$.validator.addMethod('IP1Checker', function(value) {
$("#ip2").valid();
return isValidIPAddress(value);
}, 'Invalid IP address');
$.validator.addMethod('IP2Checker', function(value) {
return isValidIPAddress(value);
}, 'Invalid IP address');
$('#form1').validate({
rules: {
ip: {
required: true,
IP1Checker: true
},
ip2: {
required: true,
IP2Checker: true
}
}
});
function isValidIPAddress(value) {
var isValid = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(value);
if (isValid && (value === "0.0.0.0" || value === "255.255.255.255")) {
isValid = false;
}
return isValid;
}
}));
</script>
</head>
<body>
<form id="form1">
<input id="ip" name="ip" type="text" />
<input id="ip2" name="ip2" type="text" />
<input id="Submit2" type="submit" value="submit" />
</form>
</body>
</html>
Thanks.
First off, jQuery v1.4.2 and jQuery Validate v1.7 are ridiculously old (circa 2010) and should be updated.
$.validator.addMethod('IP1Checker', function(value) {
$("#ip2").valid(); // <- you shouldn't do this
return isValidIPAddress(value);
}, 'Invalid IP address');
You should not call .valid() from within the .addMethod() method as it could potentially throw everything into a loop. The .addMethod() method is only intended for creating a new validation rule, not for other functions such as programmatically triggering the validation test. (The validation test runs all rules on a particular field or form. The validation rule evaluates one particular field against one particular rule.)
You don't even need a custom method for checking IP addresses. Simply use the ipv4 rule that's already built into the additional-methods.js file of the plugin.
$('#form1').validate({
rules: {
ip: {
required: true,
ipv4: true
},
ip2: {
required: true,
ipv4: true
}
}
});
DEMO: https://jsfiddle.net/p5gn6zhe/
As far as calling .valid() on field #2 inside the custom IP rule for field #1; it's not clearly explained why you'd want to do this. Are you wanting field #2 validation to depend on whether field #1 is filled out? If so, then that's something else entirely.
Otherwise, you would trigger .valid() using an external handler.
$('#ip').on('keyup blur', function() {
$("#ip2").valid();
});
DEMO 2: https://jsfiddle.net/p5gn6zhe/2/
I am using jQuery validation to validate multiple forms with same id. Each form contains different fields and I want to add these fields validation rules to jQuery validate function. How can I add these rules for multiple forms (every form has the same id)?
Example
Form1
<form id="new-form">
<input type="text" name="name" value=""/>
<input type="text" name="email" value=""/>
<input type="submit" name="submit" value="submit"/>
</form>
Form 2
<form id="new-form">
<input type="text" name="mobile" value=""/>
<input type="text" name="address" value=""/>
<input type="submit" name="submit" value="submit"/>
</form>
JavaScript function
$('#new-form').validate({
// I want to add rules here for both forms
});
I am using jQuery validation to validate multiple forms with same id
You cannot use the same id multiple times on the same page. It's invalid HTML and it will break your JavaScript. Only the first instance of an id will be considered.
If you change your id into a class, then you can freely use it multiple times, and it's valid HTML.
<form class="new-form">...</form>
<form class="new-form">...</form>
However, the jQuery Validate plugin will still only consider the first instance (a limitation of this particular plugin). The workaround is to use a jQuery .each() together with class naming...
$('.new-form').each(function() { // select every form on the page with class="new-form"
$(this).validate() { // initialize plugin on every selected form
// rules for both forms
});
});
Each form contains different fields and I want to add these fields validation rules to jQuery validate function.
Simply declare all the rules for both forms. The plugin will ignore any field names that do not exist on the form.
$('.new-form').each(function() { // select every form on the page with class="new-form"
$(this).validate() { // initialize plugin on every selected form
rules: {
name: {
required: true
},
email: {
required: true
},
mobile: {
required: true
},
address: {
required: true
}
},
// other options, etc.
});
});
That is not possible reason same id is not working so change id name.then use below code:
$().ready(function() {
// First form validate
$("#commentForm").validate();
// Second form validate
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
}
}messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
}
});
});
From the documentation http://1000hz.github.io/bootstrap-validator/:
Add custom validators to be run. Validators should be functions that receive the jQuery element as an argument and return a truthy or falsy value based on the validity of the input.
Object structure is: {foo: function($el) { return true || false } }
Adding the validator to an input is done just like the others, data-foo="bar".
You must also add default error messages for any custom validators via the errors option.
I don't quite understand how to define my own custom validator and how to use it with this plugin.
Could anyone give me a simple example or hint?
You need to call your plugin manually, as custom options will not work with data-attributes:
$().validator({
custom: {
'odd': function($el) { return Boolean($el.val() % 2);}
}
})
then use it like this:
<input placeholder="plz enter odd value" data-odd>
Don't forget to add error messages, see code
I wanted to flesh out the answers here with a bit more detail.
I was attempting to do this while using the data-api (putting data-toggle="validator" in the form tag). Removing that from my <form> tag and enabling it with Javascript, my custom function works:
$('#sign-up_area').validator({
custom: {
'odd': function($el) { return Boolean($el.val() % 2);}
},
errors: {
odd: "That's not an odd number!"
}
});
I also had to add a value to the data-odd attribute thusly:
<div class="row">
<div class="form-group col-xs-12 col-md-12">
<label class="control-label" for="test">Odd/Even:</label>
<input type="text" name="test" id="test" class="form-control" placeholder="Enter an odd integer" data-odd="odd" >
<span class="help-block with-errors"></span>
</div>
</div>
Interesting to note that if I add the following to the <input> element, it takes precedence over the error message declared in javascript:
data-odd-error="Not an odd number, yo!"
However, I get an error in console if I only use the data-odd-error attribute but NO error message specified in Javascript. Thus, you must declare an error message in Javascript.
First of all add your own custom validator, for example:
var validatorOptions = {
delay: 100,
custom: {
unique: function ($el) {
var newDevice = $el.val().trim();
return isUniqueDevice(newDevice)
}
},
errors: {
unique: "This Device is already exist"
}
}
Second, you need to "bind" the form input for the custom validator, for example:
<input id="add_new_device_input" class="form-control" data-unique="unique">
If you want to add to this input more validators error you must to add the custom error to the input: data-unique-error="This device is already exist"
for example:
<input id="add_new_device_input" class="form-control" data-unique="unique" data-unique-error="This device is already exist" data-error="The Device pattern is invalid" pattern="<Add some regex pattern here>">
The "data-error" is the default validator error and it called "native" key, the following code will demonstrate how the validator print the error messages according to the validator key:
function getErrorMessage(key) {
return $el.data(key + '-error')
|| $el.data('error')
|| key == 'native' && $el[0].validationMessage
|| options.errors[key]
}
Ні, all!
I have a little question about jQuery.Validation plugin: - Can I complete validation for input fields that are not form fields (i.e no in the "form" tag) using jQuery.Validation plugin?
Thanks.
Yes you can, but the field still needs to be inside a set of <form> tags. However, you do not need to "submit" this form in order to check validation on the field(s) inside. You use the .valid() method to check this form independently of form submission.
http://jsfiddle.net/9fgVN/13/
<form id="myNonsubmitForm" action="#">
<textarea name="comments" id="comments" rows="5" cols="30"></textarea>
</form>
<button id="myButton">Click to Check Validation Status</button>
<input type="text" id="output" />
$(document).ready(function() {
$("#myNonsubmitForm").validate({
validClass: 'valid', // as per your configuration
rules: { // set rules as per your configuration
comments: {
required: false,
maxlength: 10
}
},
errorPlacement: function(error, element) {
// use this to control placement of error messages
// removal of errorPlacement handler will result in message appearing next to field automatically.
}
});
$("#myButton").click(function() { // validate on button click for this example
if($("#myNonsubmitForm").valid()){
$('#output').val('passed');
} else {
$('#output').val('failed');
};
});
});