jQuery Validation - .valid method first attempt fails to validate - javascript

I am trying to programatically check the validity of my form the code snippet below gives true on the click of button "#btnSet" even if I enter an invalid value in the email field if I click on it again than it gives false.
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
var validator = $("#myForm").validate({
rules:{
cen:"email",
frm:{email:true,required:true},
sub:{required:true, minLength:3,maxLength:50},
fn:{required:true,minLength:3,maxLength:50},
forCols:{regex:"^[1-9]?[1-9](,[1-9]?[1-9])*$"},
ftrCols:{regex:"^[1-9]?[1-9](,[1-9]?[1-9])*$"}
}
});
$("#btnSet").on("click",(function(validator){
return function(){
alert(validator.valid());
if(!validator.valid()){
validator.showErrors();
return;
}
}
}(validator)));
If I replace the click event handler with this function
$("#btnSet").on("click",function(){
alert($("#myForm").valid());
if(!$("#myForm").valid()){
return;
}
});
It give the error below
a.validator.methods[d] is undefined

a.validator.methods[d] is undefined means that you have undefined methods (rules); in other words rules that are invalid...
sub:{required:true, minLength:3,maxLength:50},
In this case, your rules are not properly spelled. It's NOT minLength and maxLength, but minlength and maxlength...
....
sub: {
required: true,
minlength: 3,
maxlength: 50
},
....

Related

parsley.js dynamic error message

I am using parsley.js with the custom validator on a select box.
I want the error message on the validator to use the currently selected option in the select box + some more text.
Unfortunately, it seems as if I am unable to change the error message dynamically.
My code
window.Parsley
.addValidator('attachedEmployee', {
requirementType: 'string',
validateString: function(value, arg1, arg2, arg3) {
var employeeID = $("#medarbejder_navn").val();
//No employee is selected if ID is 1
if(employeeID == 1)
{
//Only shifts which can be made with no employees are "accepted" and "free"
if(value == "G" || value == "L" || value == "A")
return true;
else
{
return false
}
}
else
return true;
},
messages: {
da: "%s"
}
});
It would seem the the validator adds the error message as soon as it gets attached, meaning it is locked right from the get go.
Anyone know how to get around this problem?
Just struggled with this, found the answer in multiple custom error message support per field by using parsley.js
To change the error message I'm doing this now:
window.Parsley
.addValidator('atLeast', {
validateString: function(value, requirement){
window.Parsley.addMessage('en', 'atLeast','Fill at least ' + requirement + ' input');
return this.validateAtLeast(Number(requirement)); // custom function
},
});

jQuery multiple form validation

I have multiple forms in different page, Is there a way to write a single function which would take care of validation or should i write code for each form separately.
$(document).ready(function () {
$('#fvujq-form1').validate();
$('#fvujq-form2').validate();
});
Note: Each form has its own rules.
Update:
$("form").each(function () {
$(this).validate({
rules: {
username: {
required: true
},
password: {
required: true
},
name: {
required: true,
},
cperson: {
required: true,
}
},
submitHandler: function (form) {
return false; //temporarily prevent full submit
}
});
});
Now the username and password of different form and name and person is of different form in different page. Is it right to proceed in this way of having a common form submission.
You should test using $('form').validate();, if that doesn't work, then use:
$('form').each(function(){
$(this).validate();
});
You can use the $("form") selector to validate all elements of type form if that's what you are asking for. I would not recommend that specifically for a page with multiple forms though.
If you can give each input element in your form a custom xx-field-type attribute eg:
<input type='text' xx-field-type='email'/>
You could use:
jQuery.fn.extend({
validate: function() {
var input_list = this.find("input");
for (var i = 0; i < input_list.length; i++) {
switch(input_list[i].attr("xx-field-type")) {
case 'username':
var value = input_list[i].val();
if (value.match(/^[a-z0-9]+$/) != true) {
return false;
}
break;
case 'password':
var value = input_list[i].val();
if (value.match(/[a-z]+/) != true
|| value.match(/[A-Z]+/) != true
|| value.match(/[0-9]+/) != true) {
return false;
}
break;
case 'email':
var value = input_list[i].val();
if (value.match(/^[a-z0-9]+#[a-z0-9]$/) != true) {
return false;
}
break;
default:
continue;
}
}
return true;
}
});
This would go through each input field of a form, check the value of it's xx-field-type attribute and use that to choose the rules that the value must match. Returns false if any fail otherwise returns true.
If you can't add custom attributes you could use classes but it feels hacky to denote form type using an attribute intended for setting display related stuff.
Untested
the field types I've used and the regexps are just for the purposes of demonstration.

Knockout validation on hasfocus binding

I have an issue with the knockout validation on hasfocus binding.
I am trying to validate the control and show an error message when the control looses focus. but when the form loads itself rule is getting triggered and it shows the error message.
is there anyway to tell on load of the form or when we initialize the rules not to fire?
self.lostfocus = ko.observable(false);
self.lostfocus.extend({ NoBlankValidationlookup: { params: { control: self }, message: "Search Text cannot be empty"} });
ko.validation.rules['NoBlankValidationlookup'] = {
validator: function (val, params)
{
////if the control looses focus then validate.
if (!val)
{
if (params.control.Value().length == 0)
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
},
message: 'Please enter at least 0 characters.'
};
//HTML
<div id="Div1" class="vm" style="display: block !important; text-align: left" data-bind="validationMessage:lostfocus"></div>
Please adivce.
use isModified(false) with your validated observable on form load.
so run something like this:
self.lostfocus.isModified(false)
You can add valueUpdate to specify when to call your rules, for instance:
self.lostfocus.extend({valueUpdate: 'afterKeyDown', NoBlankValidationlookup:
{ params: { control: self }, message: "Search Text cannot be empty"} });

Validate form with jquery validation plugin

I'm using jQuery Validation Plugin 1.9.0 (from http://bassistance.de/). The problem is that I can't figure out how to validate a text field only if a user type something in it. If the user did not write anything that field should not be treated as required.
Do not set the required rule option -
rules : {
text1 : {
required: false, // Or do not specify the option
minlength: 3 // validation if it has value
}
},
if ( value != '' ) {
// Do your validation here
}
You can pass a function to a validation rule. For instance
$("#demoForm").validate({
rules: {
"requiredField": {sampleRule: function(e){
var input = $(e);
if(input.val())
return true;
return false;
}
}
},
messages : {
"requiredField": "This field is invalid"
}
Where "sampleRule" can be any rule you want eg. "required" or "minlength". The function gives the power to add conditional rule.

source only allowed values in JQuery UI autocomplete plugin

Is is possible to restrict the user input to only the source values with JQuery autocomplete plugin?
For example, if the source array contains "Bold","Normal","Default","100","200", the user is allowed to only type those values.
I see you already have a solution. Here's a similar way to do this, since I already put some time in on it.
http://jsfiddle.net/pxfunc/j3AN7/
var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";
$('#ac').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
I have a simple alternative. Check this out:
http://jsfiddle.net/uwR3Z/2/
Basically an onChange event on the textbox to clear out the value works the same.
Here is the js:
var validOptions = ["Bold", "Normal", "Default", "100", "200"];
$('#auto-complete-input').autocomplete({
autoFocus: true,
source: validOptions
});
function clearAutoCompleteInput() {
$("#auto-complete-input").val('');
}
And html:
<label for="auto-complete-input">Select one: </label>
<input id="auto-complete-input" type="text" onChange="clearAutoCompleteInput()" />
I agree with the comment made by Rephael, as you want to limit the possible values to the one in autocomplete, a safer choice would be to have a select dropdown.
As a final user can be frustrating to enter data in a textbox and not being able to write what I want. The choice of a select dropdown is "socially" accepted to be limited.
I figured out a way.
Add the following option to the plugin. This works for when the source is an array.
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
$.each(YOUR_SOURCE_ARRAY_NAME, function (index, value) {
if (value.match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
return false;
}
}
}
This is an old question but I what I do is
set a flag to false when entering the field (onfocus)
Set the flag to true in the autocomplete select event
Test that flag in the field onblur event.
If it is true the input is good, otherwise it is bad.

Categories