Custom validation with ajax.....Here remote method is not working - validation

I am using jquery.validate.js, in the code below both remote and regex works separately but when I try to integrate both then it is not working. Can anybody help me where I did wrong?
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#clear").click(function(){
$("input[type=text], textarea").val("");
});
});
function submitForm() {
$.validator.addMethod("subTitleVal", function(value, element) {
return this.optional(element) || /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement : function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules : {
name : {
required : true,
subTitleVal : true,
remote: {
type: 'POST',
url: "${pageContext.request.contextPath}/company/getDuplicate",
data: {"name":name},
dataType : "json",
success:function(data){
/* response = ( data == true ) ? true : false; */
if (data.name == true)
{
message: {
name: 'The username is already in use!'
}
}
}
},
}
},
},
errorElement : "span",
wrapper : "span",
messages : {
name : {
required : "Name Is Required",
}
}
});
if(validator.form()){
$('form#company').submit();
}
};
</script>
</head>
<body>
<form:form commandname="company" action="${pageContext.request.contextPath}/company/create.action" method="post" modelAttribute="company" name="theform">
<label>Name:</label>
<form:input path="name" id="name"></form:input>
Add
</form:form>
</body>
please help. Thanks

replace your code with this
function submitForm() {
$.validator.addMethod("subTitleVal", function(value, element) {
return this.optional(element)
|| /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement : function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules : {
name : {
required : true,
subTitleVal : true,
remote : {
type : 'POST',
url : "${pageContext.request.contextPath}/company/getDuplicate",
data : {
name: function() { return $("#name").val(); }
}
}
}
},
errorElement : "span",
wrapper : "span",
messages : {
name : {
required : "Name Is Required",
remote : "Name Already Taken."
}
}
});
if (validator.form()) {
$('form#company').submit();
}
};

From the documentation
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements, using
the default message; or a string, eg. "That name is already taken, try
peter123 instead" to display as the error message.
So your validation url must return an appropriate value
Try
function submitForm() {
$.validator.addMethod("subTitleVal", function(value, element) {
return this.optional(element)
|| /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement : function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules : {
name : {
required : true,
subTitleVal : true,
remote : {
type : 'POST',
url : "${pageContext.request.contextPath}/company/getDuplicate",
data : {
"name" : name
}
}
}
},
errorElement : "span",
wrapper : "span",
messages : {
name : {
required : "Name Is Required"
}
}
});
if (validator.form()) {
$('form#company').submit();
}
};

Your brackets are not closed properly. You have an extra },
Keep your code well-indented to avoid such minor mistakes in the future.
This should be your code instead:
function submitForm() {
$.validator.addMethod("subTitleVal", function (value, element) {
return this.optional(element) || /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement: function (error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules: {
name: {
required: true,
subTitleVal: true,
remote: {
type: 'POST',
url: "${pageContext.request.contextPath}/company/getDuplicate",
data: {
"name": name
},
dataType: "json",
success: function (data) {
/* response = ( data == true ) ? true : false; */
if (data.name == true) {
message: {
name: 'The username is already in use!'
}
}
}
},
}
},
errorElement: "span",
wrapper: "span",
messages: {
name: {
required: "Name Is Required",
}
}
});
if (validator.form()) {
$('form#company').submit();
}
};

Related

how to change data sorting in kendo ui donut chart series categoryField?

i'm mina.
I would like to specify the order of data in series categoryFiled.
categoryField has received a status value.
status has 0, 1, and 2 status values.
status 0 : disconnct
status 1 : connect
status 2 : running
Can I get the order of 2,1,0 using the sort option?
this is my code :
var toKorean = (function(){
var set = {
"RUNNING" : /*[[#{dashboard.Executing}]]*/,
"CONNECT" : /*[[#{dashboard.Connect}]]*/,
"DISCONNECT" : /*[[#{dashboard.Disconnect}]]*/,
};
return (function(status){
for(var i in set)
{
console.log(status);
if(i == status)
{
return set[i];
}
}
})
})();
function createChart(type) {
$( "#"+type ).kendoChart({
transitions: false,
renderAs: "canvas",
dataSource: {
transport: {
read: {
url: "dashboard/" + type +".json",
dataType: "json"
}
},
schema:{
data: function(response){
console.log(response);
for(i in response)
{
var status = response[i].status;
response[i].status = toKorean(status);
}
return response;
}
},
sort : {
field: "status",
},
},
seriesDefaults: {
type: "donut",
labels: {
visible: true,
background: "transparent"
},
overlay: null
},
seriesColors:["#fd5a21","#ffde43","#66ccff"],
series: [{
field: "count",
categoryField: "status",
padding: 0
}],
});
}

Prop mutating warning in VUE

I got an vue-warning (which results to as an error on my end coz my code is not working) that says:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "editmode"
With it, tried the suggestion here but can't make it work. Below is my work:
props:{
editmode:{
type: Boolean,
default: false,
}
},
methods:{
toggleM(){
var editmode = this.editmode;
editmode = !editmode;
this.editmode = editmode;
if(editmode == false){
//dothis
}else{
//dothat
}
},
}
TEMPLATE
<template>
<div class="ui-table-container-body">
<div class="ui-table" v-if="Boolean(items.length) || Boolean(Object.keys(items).length)" v-cloak>
<ui-table-body ref="body" v-model="items"
:editmode="editmode"
>
</ui-table-body>
</div>
</div>
</template>
The line this.editmode = editmode; is the one pointed in my console, is there any way I can surpass this?
You must use a data variable as a gateway to your prop.
In your component, the code code should look like this:
props:{
editmode:{
type: Boolean,
default: false,
}
},
data: {
dataEditMode = false
},
watch: {
'editmode': {
handler: 'onEditmodeChanged',
immediate: true,
},
'dataEditMode': {
handler: 'onDataEditModeChanged'
}
},
methods:{
toggleM(){
var editmode = this.dataEditMode;
editmode = !editmode;
this.dataEditMode = editmode;
if(editmode == false){
//dothis
}else{
//dothat
}
},
onEditmodeChanged (newVal) {
this.dataEditMode = newVal
},
onDataEditModeChanged (newVal) {
this.$emit('editmodeChanged', newVal)
}
}
and the the inclusion of this component in your parent-component should look like this:
<my-component-name :editmode="editmode" #editmodeChanged="(e) => { editmode = e }"></my-component-name>
You shouldn't mutate props from the component itself. See the One Way Data Flow section of the guide. You can use a prop as the initial value, and then keep a value in the data section and mutate that:
props: {
editmode: {
type: Boolean,
default: false,
}
},
data () {
return {
emode: this.editmode,
}
},
methods: {
toggleM () {
let editmode = this.emode;
editmode = !editmode;
this.emode = editmode;
if (editmode == false) {
// dothis
} else {
// dothat
}
},
}
Demo
Vue.component('editbox', {
template: '<div>' +
'<button #click="toggleM">{{ btext }}</button>' +
'<input v-if="emode" />' +
'</div>',
props: ['editmode'],
data () {
return {
emode: this.editmode,
}
},
computed: {
btext () {
return this.emode ? "Text" : "Edit";
}
},
methods:{
toggleM() {
this.emode = !this.emode;
},
}
})
var app = new Vue({
el: '#app',
data: {
mode: true,
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<editbox :editmode="mode" />
</div>
I would send back an event to the parent so it could modify its value:
For example (not tested):
Child Component
props:{
editmode:{
type: Boolean,
default: false,
}
},
methods:{
toggleM(){
var editmode = !this.editmode;
this.$emit('changeEditMode', editmode);
if (editmode == false){
//dothis
} else {
//dothat
}
},
}
Parent
<child-component #changeEditMode="editModeChanged" :editmode="editmode"></child-component>
...
methods:{
editModeChanged(value){
this.editmode = value
},
}

Kendo UI Server side sorting and filtering

Given below kendo dataSource which is calling API though services.
It is difficult to identify whether sorting or filtering event is triggered.
var dataSource = new kendo.data.DataSource({
transport: {
// read : "/scripts/data/products/categoryLabel.json",
read : function(options){
// alert(options.data.page + "-" + options.data.pageSize);
console.log("Read options : " , options);
var order_by;
if (options.data.sort) {
if (options.data.sort.length > 0) {
var sortField = options.data.sort[0].field;
if (options.data.sort[0].dir == 'asc') {
var sortOrder = '';
}
else if (options.data.sort[0].dir == 'desc') {
var sortOrder = '-';
};
order_by = sortOrder + sortField;
}
}
if (options.data && options.data.filter && options.data.filter.filters) {
config ={
value: options.data.filter.filters[0].value,
field: options.data.filter.filters[0].field,
accountId: $scope.model.adAccount.accounts.selected.aa_id,
category_id : null,
};
console.log("input: ", options.data.filter.filters[0])
}
Campaignlabel.fetchCategorycampaign(config, order_by, options.data.page, options.data.pageSize).success(function (fetchCampaignlabel) {
$scope.model.totalCount = fetchCampaignlabel.count;
options.columns = $scope.model.columns;
options.success(fetchCampaignlabel.results);
// config = null;
}).error(function (fetchCampaignlabel) {
options.error(fetchCampaignlabel.results);
});
},
},
pageable : true,
pageSize:50,
serverPaging: true,
reorderable: true,
sortable :true,
page : 1,
serverFiltering: true,
serverSorting: true,
schema: {
total: function (result) {
result = result.data || result;
return $scope.model.totalCount;
},
model: {
id : "campaign_id",
fields: {
Select : {type : "boolean"},
category: { editable: false, type: 'number'},
campaign_id: { editable: false, type: 'number'},
name: { editable: false, type : "string" },
objective: { editable: false, type : "string" },
status: { editable: false, type : "string" },
category_name: { editable: false },
start_time : { editable: false, type: "date"},
}
}
},
});
Please suggest any way to identify filter or sorting event here.

How to reload Fuelux Tree with new data

Here i'm trying Fuelux Tree used in Ace admin Template. I have used the same code they have used.
The script code used in ace admin template:
jQuery(function($) {
var tree_data = {};
var sampleData = initiateDemoData(tree_data); //see below
$('#tree1')
.ace_tree({
dataSource: sampleData['dataSource1'],
multiSelect: true,
cacheItems: true,
'open-icon': 'ace-icon tree-minus',
'close-icon': 'ace-icon tree-plus',
'selectable': true,
'selected-icon': 'ace-icon fa fa-check',
'unselected-icon': 'ace-icon fa fa-times',
loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>'
});
function initiateDemoData(tree_data) {
tree_data = {
"2C27D744B956": {
"text": "2C27D744B956",
"children": {
"001B179F4400": {
"text": "9991100003333",
"type": "item"
},
"9991100003333": {
"text": "9991100003333",
"type": "item"
},
"2c27d744b956": {
"text": "9991100003333",
"type": "item"
},
"002170615A04": {
"text": "9991100003333",
"type": "item"
}
},
"type": "folder"
}
};
var dataSource1 = function(options, callback) {
var $data = null
if (!("text" in options) && !("type" in options)) {
$data = tree_data; //the root tree
callback({
data: $data
});
return;
} else if ("type" in options && options.type == "folder") {
if ("children" in options)
$data = options.children || {};
else
$data = {} //no data
}
if ($data != null) //this setTimeout is only for mimicking some random delay
setTimeout(function() {
callback({
data: $data
});
}, parseInt(Math.random() * 500) + 200);
//we have used static data here
//but you can retrieve your data dynamically from a server using ajax call
//checkout examples/treeview.html and examples/treeview.js for more info
}
return {
'dataSource1': dataSource1
}
}
});
Then on a button click i'm trying to refresh the tree, with new data from ajax Get request, But when i tried, an error comes in browser such as "Uncaught TypeError: Cannot read property 'apply' of undefined ".
Following is my ajax code:
$.ajax({
type : "GET",
url : "getDevices.htm?did=" + dID,
success : function(data) {
tree_data = data; //tree_data is the data used for the treeview
$('#tree1').tree('reload');
},
error : function(data) {
console.log("failure" + data);
}
});
Please suggest a method to resolve this issue.
Thanks in advance.

DataTable + JEditable + AutoComplete(BAssistance) + Server Side Processing

After almost struggling for a week I have been able to make DataTable + JEditable + AutoComplete(BAssistance) with server side processing using Json to work.
I thought it would be useful to somebody out there.
$(document).ready(function() {
$('#example tbody td').editable(
function(value, settings) {
processEventForTable(this, value);
return(value);
},
"height": "20px"
});
oTableexample = $('#example').dataTable({
"bInfo": true,
"bProcessing" : true,
"bServerSide" : true,
"sAjaxSource" : "GetPaginationData.aspx",
"sPaginationType": "full_numbers",
"bPaginate" : true,
"fnServerData": function ( sSource, aoData, fnCallback ) {
var data = {"name" : "kObjectId",
"value" : definitionId};
aoData.push(data);
data = { "name" : "ObjectName", "value" : "example" };
aoData.push(data);
data = { "name" : "InstanceId", "value" : instanceId };
aoData.push(data);
data = { "name" : "IsNewRequest", "value" : IsNewRowAdded};
IsNewRowAdded = 0;
aoData.push(data);
debugger;
$.ajax( {
"dataType": 'json',
"type": "Get",
"url": sSource,
"data": aoData,
"success": fnCallback
});
},
"fnDrawCallback" : function() {
debugger;
SetDataTableIDAndAttachJEditable("example");
$('#example tbody td').editable( function(value, settings)
{
var aPos = oTableexample.fnGetPosition( this );
processEventForTableNew(aPos[0], aPos[1], value, "example");
return(value);
}
);
}
});
$.editable.addInputType('autocomplete', {
element : $.editable.types.text.element,
plugin : function(settings, original) {
$('input', this).autocomplete(settings.autocomplete.url, {
dataType:'json',
parse : function(data) {
return $.map(data, function(item) {
return {
data : item,
value : item.Key,
result: item.value
}
})
},
formatItem: function(row, i, n) {
return row.value;
},
mustMatch: false,
focus: function(event, ui) {
$('#example tbody td[title]').val(ui.item.label);
return false;
}
});
}
});
$("#example tbody td > span[title]").editable(
function(value,settings){
return value;
},
{
type : "autocomplete",
tooltip : "Click to edit...",
autocomplete : {
url : "autocompleteeg.aspx"
}
}
);
});
This code works perfectly fine.
DataTables use Server Side Processing. And I am submitting the changes to JEditable to javascript function. From there on Submit I am submitting the entire change array to server.
This code has become too long can anybody help me refactor it.
If there is any better way to accomplish the same thing then I am waiting for it. :)
Yeah cool Dude !
Just a small syntax error in your code.
} , { // opening bracket missing
"height": "20px"
}
Thanks a lot

Resources