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"} });
Related
I have a field with about eight required fields. I have some code that only enables a button if all fields are validated. Then, I have a method that checks to see if all fields are valid - only then is the button enabled.
$("#FirstName").on("keyup blur", function () {
if ($("#FirstName").length > 0) {
if ($("#FirstName").valid()) {
isFirstNameValid = true;
}
else
isFirstNameValid = false;
checkIfAllFieldsAreValid();
}
})
The issue is that the required validation field is throwing an error when I tab to the next field, because the "keyup blur" event is firing on the next field even before I start typing. What event prevents this behavior from happening?
You can leave the submit button enabled and check when the user clicks it if the form is valid or not
$("#btnCreateMyAccount").on("click", function () {
if ($("#CreateAccountForm").valid()) {
return false;
}
else
{
//submit the data
}
})
Try checking if any of the inputs are empty before validating the form.
if($("your input field").val()=="") {
return;
}
Working on jQuery validator initially some of the field where display none so when the user click next button the error message was showing You have missed 1 fields. Please fill before submitted this was working perfect as i expected. Because I gave ignore:".chk_Field",. But when the user click yes radio button user can able to see some more fields. without filling any of the field If user click the next button still it should say You have missed 5 fields. Please fill before submitted but currently it was saying You have missed 1 fields. Please fill before submitted this is not happening with this line of code ignore:".chk_Field",
Here is my jquery code
function apply_validation() {
$(".educationForm").validate({
ignore:".chk_Field",
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = 'You have missed ' + errors + ' fields. Please fill before submitted.';
$errorMessageDiv.html(message);
$errorMessageDiv.show();
} else {
$errorMessageDiv.hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if ($(element).is(':radio')) {
} else {
$(element).addClass('errRed');
$(".chk_field_hlt").addClass('errRed_chkb');
$('#imageUploadForm').addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if ($(element).is(':radio')) {} else {
$(element).removeClass('errRed');
$(".chk_field_hlt").removeClass('errRed_chkb');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
}
});
}
Here is the fiddle link
Thanks in advance
Try to put this line of code:
$("#expy").find(".chk_Field").removeClass("chk_Field");
Here:
$(".wrk_clp").click(function () {
if ($('input[name=rad_emp]:checked').val() == "yes") {
$expDiv.show();
$("#expy").find(".chk_Field").removeClass("chk_Field");
}
I just tested and it seems to work.
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.
I'm running into issues with the following code:
var setupSearch = {
searchSuggest: function(field) {
$.getJSON('/get-all-journals', {'url':'on'}, function(data) {
var SHCount = Number($.cookie('SHCount'));
var SHArray = new Array();
for (i=1; i <= SHCount; i++) {
SHArray.push($.cookie('SH'+i));
}
$(field).ddautocomplete(removeDuplicate(SHArray), data.response.docs, {
matchContains: true,
max: 5,
cacheLength: 5000,
selectFirst: false,
scroll: false,
formatResult: function(str) { return str; },
formatItem2: function(item) {
return item.journal_display_name;
},
formatMatch2: function(item) {
return item.journal_display_name;
},
formatResult2: function(item) {
return item.journal_display_name;
}
});
});
},
searchForm: function(form) {
var field = form.find('textarea');
// Setup query field for default text behavior
// setupField(field);
setupSearch.searchSuggest(field);
field.autogrow();
field.keydown(function(e) {
if (e.keyCode == 13) {
form.submit();
return false;
}
});
// Make all forms submitting through Advanced Search Form
form.submit(function(e) {
e.preventDefault();
setupSearch.submitSearch(form, field);
});
},
submitSearch: function(form, field) {
if (advancedSearch.checkMinFields() || (!field.hasClass('defaultText') && field.val() != '')) {
// Sync the refine lists
// syncCheckboxLists($('#refineList input'), $('#advancedRefineList input'));
form.find('button').addClass('active');
$('#advancedSearchForm').submit();
} else {
$('#queryField').focus();
}
},
When I try to use the autocomplete drop-down by hitting enter, it seems to hit a "race condition" where the form will submit what I've typed rather than what autocomplete places into the textfield. Is there some way I can control the order of events so that the form.submit() will use what autocomplete fills into the text field?
The actual autocomplete dropdown menu is most likely represented as a styled list (or some other element) that is floated to be positioned below the textbox. On submit, have your function wait (a second or two max) for the autocomplete menu to be either destroyed or hidden. This will ensure that the plugin has time to fill in the textbox before the data is submitted.
EDIT
Try something like this:
$("#myDropdown").bind("autocompleteclose", function(){
// Continue with submitting your form
});
Use that where you would submit your form, and put the submitting code inside the callback. That way, it will wait for the autocomplete to close before submitting the form. You will want to add some kind of timeout to this to prevent it from submitting after a long delay (not sure when something like this might happen, though).
Any tips for form validation using jeditable. I would like to have the script POSTed to pass back errors with JSON, with the submitted text but can't seem to figure that one out, if even possible. Or how to check text as it's being inputed via onChange.
Thx
Here is a simple sample, but not used jQuery Validation.
function isNumeric(value) {
if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
return true;
}
$('.edit').editable(your_url, {
onsubmit: function(settings, original) {
if (isNumeric(original)) {
return true;
} else {
//display your message
return false;
}
}
});