Jquery Validation Rules for comparing two numbers - php

I have these two Input boxes
form_open('performances/save/'.$performance_info->prf_id,array('id'=>'performance_form'));
form_input(array(
'class'=>'beg_inv',
'name'=>'beg_inv',
'id'=>'beg_inv',
'value'=>$performance_info->beg_inv);
form_input(array(
'class'=>'end_inv',
'name'=>'end_inv',
'id'=>'end_inv',
'value'=>$performance_info->end_inv);
form_submit(array(
'name'=>'submit',
'id'=>'submit',
'value'=>$this->lang->line('common_submit'),
'class'=>'submit_button float_right')
);
and i am using this jquery validate:
$('#performance_form').validate({
submitHandler:function(form)
{
$('#prf_id').val($('#scan_performance').val());
$(form).ajaxSubmit({
success:function(response)
{
tb_remove();
post_exp_form_submit(response);
},
dataType:'json'
});
},
errorLabelContainer: "#error_message_box",
wrapper: "li",
rules:
{
prod_id:"required",
beg_inv: { greaterThan: "#end_inv" }
},
messages:
{
prod_id:"<?php echo $this->lang->line('performances_product'); ?>",
beg_inv:"<?php echo $this->lang->line('performances_qty_val'); ?>"
}
});
I used the greaterThan as I have seen in this url but that is for dates only I think because my code above does not work. What is the equivalent of the greaterThan for numbers? Or are there any?
EDIT:
adding this worked out, new question: How do I Validate again when I corrected the end_inv without going back to the beg_inv to trigger the rule. If I add a new rule it will create a new error line instead of overwriting the first error message. Fiddle here by Riley
$.validator.addMethod(
"greaterThan",
function (value, element, params)
{
var target = $(params).val();
var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
if (isValueNumeric && isTargetNumeric) {
return Number(value) > Number(target);
}
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date(target);
}
return false;
}, 'Must be greater than {0}.');

Related

select2 on success retrieve newly created tag id

In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_tags').on("change", function(e) {
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag " + e.added.id + "?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.

How to autocomplete bootstrap tokenfield with ajax?

I want to use the tokenfield for bootstrap: http://sliptree.github.io/bootstrap-tokenfield/ but I can't seem to find any documentation on how to do it using AJAX. I have a .php file with json data like this {"Hello", "Helium", "Hell"} and I want it to be the autocomplete values. Please note that the .php file only returns values that are similar to what is being typed. Can anyone find a way to do this? Any help would be highly appreciated. I just wanna use that gorgeous bootstrap tokenfield to autocomplete tags and disallow autocomplete if the word's don't exist there.
Thanks.
You need to implement either autocomplete from jquery-ui or typeahead from twitter, and then apply specific options.
$('#activity_tag_tokens').tokenfield({
typeahead: {
prefetch: '/tags.json',
remote: '/tags.json?q=%QUERY',
}
});
Bootstrap tokenfield - typeahead autocomplete with remote call using ajax
Prerequisitics:
= stylesheet_link_tag 'sales_crm/tokenfield-typeahead.css'
= stylesheet_link_tag 'sales_crm/bootstrap-tokenfield.css'
%script{:src => "//code.jquery.com/ui/1.10.3/jquery-ui.js", :type => "text/javascript"}
= javascript_include_tag "sales_crm/bootstrap-tokenfield.js"
= javascript_include_tag "sales_crm/typeahead.bundle.min.js"
In HAML View File:
%input#tokenfield-typeahead.form-control.add_locality_data{:type => "text", :value => "", :identifier=> "Locality"}/
1) Initialize the BloodHound search engine
var engine = new Bloodhound({
remote: {
url: '/sales_crm/leads/get_lead_associated_info?query=%QUERY&model_class='+$('.add_locality_data').attr("identifier"),
filter: function (response) {
var tagged_user = $('#tokenfield-typeahead').tokenfield('getTokens');
console.log(tagged_user)
return $.map(response.leads, function (user) {
console.log(user)
var exists = false;
// console.log("velava saranam");
for (i=0; i < tagged_user.length; i++) {
if (user.value == tagged_user[i].value) {
var exists = true;
}
}
if (!exists) {
return {
value: user.value,
label: user.label
};
}
});
}
},
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
2) Then Initialize tokenfield function
$('#tokenfield-typeahead').tokenfield({
delimiter: false,
typeahead: [
{
name: 'users',
displayKey: 'label',
source: engine.ttAdapter()
}
]
})
.on('tokenfield:createtoken', function (e) {
var existingTokens = $(this).tokenfield('getTokens');
if (existingTokens.length) {
$.each(existingTokens, function(index, token) {
console.log(token)
if (token.value === e.attrs.value) {
e.preventDefault();
}else{
console.log(e.attrs.value)
}
});
}else{
console.log(e.attrs.value)
}
});
It's OK ... I find the solution
$('#tokenfield1').tokenfield();
var mots_cles = "";
$.each(e.valeur_tableau_infos_tutoriel.Mots_cles, function (index,value){
mots_cles += value.mots_cles+',';
})
$('#tokenfield1').tokenfield('setTokens', mots_cles)
}

How can I add a jqGrid custom error message?

I´m using CodeIgniter and JQuery Grid. I have seen the responses that you have been made here about this topic but I haven't been able to solve my problem with none of them.
The fact is that I have a jqGrid and I need to show the the dialog of insert several types of error that the database server returns.
For example, in one case I have this error:
Duplicate entry '18-2-1-2012-10-25' for key 'user_store_turn_index'
I need to get this and to show a custom message instead of the current:
error Status: 'Internal Server Error'. Error code: 500
I've tried with the aftersubmit event. I've read the docs and seen the available examples but nothing works.
Inside my JavaScript code I have the function that deals with the after submit event for jqGrid:
afterSubmit : function(response, postdata){
test_validate
return false;
},
}
Then, I write the function that should get the responses for the after submit event:
function test_validate(response,postdata) {
alert('test');
if(response.responseText == '') {
success = true;
} else {
success = false;
}
return [success,response.responseText]
}
But nothing happens... Here is the almost complete jquery grid code
$(document).ready(function() {
var grid = jQuery("#newapi_1351189510").jqGrid({
ajaxGridOptions : {type:"POST"},
jsonReader : {
root:"data",
repeatitems: false
},
rowList:[10,20,30],
viewrecords: true
,url:'http://localhost/sp/index.php/turn_open/getData'
,editurl:'http://localhost/sp/index.php/turn_open/setData'
,datatype:'json'
,rowNum:'20'
,width:'600'
,height:'300'
,pager: '#pnewapi_1351189510'
,caption:'Apertura de caja'
,colModel:[
{name:'username',index:'username',label:'Usuario' ,align:'center',width:180,editable:false }
,{name:'TurnName',index:'TurnName',label:'Turno' ,align:'center',width:180,editable:false }
,{name:'date',index:'date',label:'Fecha' ,width:100,editable:true,edittype:'text',editrules:{required:false,date:true} ,editoptions: {size: 10, maxlengh: 10,dataInit: function(element) { $(element).datepicker({dateFormat: 'yy-mm-dd',changeMonth: true,changeYear: true,yearRange: '1982:2022'})}},searchoptions: {size: 10, maxlengh: 10,dataInit: function(element) { $(element).datepicker({dateFormat: 'yy-mm-dd',changeMonth: true,changeYear: true,yearRange: '1982:2022'})}}}
] })
jQuery("#newapi_1351189510")
.jqGrid('navGrid',
'#pnewapi_1351189510',
{view:false,
edit:'1',
add:'1',
del:'1',
close:true,
delfunc: null
},
afterSubmit : function(response, postdata)
{ test_validate
return false;
},
},
{mtype: 'POST'} /*delete options*/,
).navButtonAdd('#pnewapi_1351189510',
{ caption:'', buttonicon:'ui-icon-extlink', onClickButton:dtgOpenExportdata, position: 'last', title:'Export data', cursor: 'pointer'}
);
;
function test_validate(response,postdata){
alert('test');
if(response.responseText == ''){
success = true;
}else{
success = false;
}
return [success,response.responseText]
}
});

Jquery and ajax, my function for username checking?

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

livevalidation.js custom username check function

I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.
i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)
try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};

Categories