Issue when accessing const value in Laravel blade - laravel

Lang
"Min_UserName" => "Min :chars chars for username",
JQuery
$("form#registerForm").validate({
rules: {
UserName: {
required: true,
minlength: 6
}
},
messages: {
UserName: {
required: "{!! trans('Register.Required_UserName') !!}",
minlength: "{!! trans('Register.Min_UserName',
['chars' => '\App\UserMinValue::Min_UserName']) !!}"
}
}
});
Class
namespace App\Architecture\MinMaxValues;
class UserMinValue {
const Min_UserName = 6;
}
Current Output
minlength: "Min App\UserMinValue::Min_UserName chars for username",
Expected Output
minlength: "Min 6 chars for username",
Am I missing anything?

You have a quote around the Class path so string path is sent out and not the value you need, change:
['chars' => '\App\UserMinValue::Min_UserName']
To:
['chars' => \App\UserMinValue::Min_UserName]

Related

Validator Rule from addMethod always returning true

This is driving me nuts. Doing a simple check for whether or not an email address exists in my database via php using ajax in an addMethod rule to my validator. I've confirmed the php file is outputting "true" or "false" properly upon finding the email or not but the rule always returns true even though the response is correct and the value is false.
This is the rule:
$.validator.addMethod("isExisting", function() {
var checkemail=$("#email").val();
console.log('Email: '+checkemail); // shows email populated correctly
if(checkemail){
$.ajax({
type: 'post',
url: 'checkemail.php',
data: {email:checkemail,},
success: function(response){
console.log(response); // properly returns text "false" when email not found
var exists = (response=="false") ? false : true;
console.log('exists = '+exists); // is properly false
return exists; // returns false
}
});
}
});
And in the validator -
(the "isExisting" error message always pops up regardless of whether the email really exists or not):
$("#signupform").validate({
errorLabelContainer: "#errors",
errorPlacement: function (error, element) {
error.insertAfter(element);
$(element).addClass(errorClass).removeClass(validClass);
},
rules: {
fullname: {
required: true,
minlength: 2
},
email: {
required: true,
email: true,
isExisting: true
},
areacode: {
required: true,
digits: true,
minlength: 3
},
prefix: {
required: true,
digits: true,
minlength: 3
},
num: {
required: true,
digits: true,
minlength: 4
},
address: {
required: true,
},
city: {
required: true,
},
noRobot: {
isCaptcha: true,
}
},
messages: {
fullname: {
required: "Please enter your full name.<br />",
minlength: "Please enter your First and Last name.<br />"
},
email: {
required: "Please enter your email address.<br />",
email: "Please enter a valid email address.<br />",
isExisting: "There is already an account with that email address.<br />"
},
areacode: {
required: "Please enter your areacode.<br />",
minlength: "Your areacode should be 3 digits. »XXX« XXX-XXXX<br />"
},
prefix: {
required: "Please enter your phone number prefix.<br />",
minlength: "Your phone number Prefix should be 3 digits. XXX »XXX«-XXXX<br />"
},
num: {
required: "Please enter your phone number suffix.<br />",
minlength: "Your phone number Suffix should be 4 digits. XXX XXX-»XXXX«<br />"
},
address: {
required: "Please enter your Street Address for pick-up service.<br />"
},
city: {
required: "Please enter your town or city.<br />"
},
noRobot: {
isCaptcha: "Please verify that your are not a spam Robot.<br />"
}
}
});
I would think the "isExisting: true" would only validate true if the true value was returned from the response. (scratches head in frustration...)
checkemail.php:
else{
$result = mysqli_query($connect, "SELECT * FROM `customer_info` WHERE `email`='$email' LIMIT 1");
$num = mysqli_num_rows($result);
if($num > 0){
echo "true";
}
else {
echo "false";
}
}
mysqli_close($connect);
My understanding is that the validator methods should return true when the response is valid. In your case, the valid response is to not have a matching email, so you want to return true if the AJAX call returns false.
It would probably be less confusing to make this method isUnused rather than isExisting to avoid the boolean confusion, but you would need to change checkemail.php as well.
Edit: Disregard my answer above, I clearly misunderstood the problem.
I think the real issue is to do with asynchronous calls. Try setting async: false in your ajax call.

Knockout Validation onlyif object no function and pattern validation

I want to the priceMax was required, when title is empty.
I have code
self.searchParameters = {
title: ko.observable().extend({
refreshCountOffers: 500
}),
priceMax: ko.observable().extend({
required: {
onlyIf: function() {
return title==null;
}
},
refreshCountOffers: 500
})
};
,but I get error 'title is not defined'.
How to disable option, which show error for pattern validation, when user input first letter?
postCode: ko.observable().extend({
required: true,
pattern: {
message: 'Post code is not valid',
params: '[0-9]{2}-[0-9]{5}'
},
refreshCountOffers: 500
})
my jsfiddle
There are 2 problems with the onlyIf check:
you need to qualify the title property
title is observable so you need to access the value
The code below resolves both:
onlyIf: function() {
return self.searchParameters.title();
}

How to validate model using collection.create()

I'm trying to make a form validated before submit. For this, I defined a create method within the View which is responsible to call collection.create() method to create the model.
Here is a sample code:
app.ContactCreateView = Backbone.View.extend({
template: _.template($('#tpl-create-contact').html()),
initialize: function () {
this.router = new app.ContactsRouter();
this.contacts = new app.ContactsCollection();
},
events: {
'click #btn-create' : 'create',
'click #btn-cancel' : 'cancel',
},
render: function() {
this.$el.html(this.template());
return this;
},
getAttributes: function () {
console.log('getAttributes()');
var attr = {
name: $('#input-name').val().trim(),
category: $('#input-category').val().trim(),
phone: $('#input-phone').val().trim(),
email: $('#input-email').val().trim(),
};
console.log('attr : ' + JSON.stringify(attr))
return attr;
},
create: function () {
console.log('create()');
// Create the Model
this.contacts.create(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
//this.hideErrors();
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
//this.showErrors(errors);
}
});
},
The 'success' callback is well called but I don't manage to get the 'error' callback called once the model.validate() method is failing.
Here is the model with the validate method :
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
// Default attributes for the Contact
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
And the collection:
app.ContactsCollection = Backbone.Collection.extend({
model: app.ContactModel,
url: '/user',
//localStorage: new Backbone.LocalStorage('contacts-backbone'),
getById: function (iId) {
return this.where({id: iId});
},
getByName: function (iName) {
return this.where({name: iName});
}
});
I really don't understand what I'm doing wrong... If somebody can help me :-(
Regards,
when the validation is failed error callback is not called , it trigger an "invalid" event on model, and set the validationError property on the model.
method 1(listening on model):
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
//your error catched here
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
method 2 (check whether validationError property is set in your view):
create: function () {
console.log('create()');
// Create the Model
this.contactModel.save(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
this.contacts.add(this.contactModel);
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
}
});
//your error catched here
if (this.contactModel.validationError) {
alert(this.contactModel.validationError)
}
},
So I played around with this for a while in an app I'm currently working on and found it kind of irritating and never really got it to work.
Instead I went the jQuery validation route and found it very helpful for doing validations. I highly recommend checking it out! It has a lot of built in validations you can just use and you can also override the error messages that display (also built in).
Example - I wanted a number only text field (excuse the coffeescript) :).
jQuery.validator.setDefaults(
debug: true,
success: "valid")
if #model.get('number_only')
$('#number_only').validate({
debug: true,
rules: {
"number[entry]": {
required: true,
range: [#model.get('min_number'), #model.get('max_number')],
number: true
}
},
messages: {
"number[entry]": {
required: "This field is required. Please enter a numeric value.",
min: jQuery.validator.format("Please enter a value greater than or equal to {0}."),
max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
number: "Please enter a numeric value"
range: jQuery.validator.format("Please enter a value between {0} and {1}.")
}
}
})
If that doesn't really get what you want (seemed like you maybe are more interested in displaying the errors your server sends back whereas this route would more be validating the content before saving your model) let me know and I can see if I can figure out your problem.

Pass variable from kendo datasource to template

I am trying to pass a string from the kendo datasource, into a template within the grid, that is acting as the Print button. The button fires a function that opens a new link to the report server, and I need to pass a string value into the function, so that string value is then sent in the url.
I have it working if I send the datasource Id field, but if I try to send a string value (Physician), I get an 'Unexpected identifier' error. I have tried changing the coluns: field: to Physician, but get the same error.
EDIT: I can pass any int value, but it breaks if I try to send a string.
How do I pass a value other than the Id to my template?
schema: {
model: {
id: "Id",
fields: {
"ClinicName": { type: "string" },
"Physician": { type: "string" },
"Phone": { type: "string" },
"Fax": { type: "string" },
"Specialty": { type: "string" },
"Consent": { type: "date" }
}
}
},
pageSize: 10
});
function printForm(Physician) {
var stuid = $('#sisid').html().match(/\d+/);
var user = $('#user').val();
var sid = $('#sess').val();
window.open("http://#reportServer/ReportServer/Pages/ReportViewer.aspx?/SHPN/Treatment%20Form&rs:Command=Render&StudentId=" + stuid + "&SessionId=" + sid + "&CurrentUser=" + user + "&Physician=" + Physician);
};
$(document).ready(function () {
columns: [
{
field: "Id",
width: "38px",
title: "Print",
filterable: false,
sortable: false,
template: "<a class='change-image' href='javascript:void(0);' title='Print Treatment Form' onclick='printForm(#= Id #)'><img alt='Student Info' src='#Url.Content("~/Content/Images/printer-icon.png")' /></a>"
},
Since Physician is a string you are probably not correctly escaping it. Try defining the template as:
template: "<a class='change-image' href='javascript:void(0);' title='Print Treatment Form' onclick='printForm(\"#= Physician #\")'><img alt='Student Info' src='#Url.Content("~/Content/Images/printer-icon.png")' /></a>"
Check it here: http://jsfiddle.net/OnaBai/ZwXa2/
columns.Bound(m => m.Name).Title("Subsys #").ClientTemplate("#= Name #");
This is razor syntax, you can insert some arbitrary string like this 'stringValue'

extjs4 data.store use with proxy

I want to get data from Yii controller action in Ext.data.store with following code:
var vehicles = new Ext.data.Store({
reader: new Ext.data.JsonReader({
fields: ['vehiclename'],
root: 'vehicles'
}),
proxy: new Ext.data.HttpProxy({
url: '<?php echo $this->createUrl('GetVehicles');?>'
}),
autoLoad: true
});
or following code for vehicles:
var vehicles = Ext.create('Ext.data.Store', {
fields: [
{name: 'vehiclename'}
],
proxy: {
type: 'ajax',
url: '<?php echo $this->createUrl('GetVehicles'); ?>',
reader: {
type: 'json',
root:'vehicles'
}
},
autoLoad: true
});
My action code is:
public function actionGetVehicles()
{
$sql = "select vehicleName from vehicletbl inner join companytbl on vehicletbl.companyid=companytbl.companyid and companytbl.companyid='2';";
$vehicles = Yii::app()->db->createCommand($sql)->queryAll();
//var_dump($vehicles);
echo '{vehicles:'.json_encode($vehicles).'}';
}
When i send request to action with browser address bar i get following json:
{vehicles:[{"vehiclename":"pride"},{"vehiclename":"benz"}]}
but i don't know why Ext.data.store can't get data and store themes!
What is wrong in my code?
I use store at:
items: [treePanel,Ext.create('Ext.grid.PropertyGrid', {
title: 'History',
closable: false,
header: true,
sortableColumns: false,
customEditors: {
Vehicle: Ext.create('Ext.form.ComboBox', {
store: vehicles,
queryMode: 'local',
displayField: 'vehiclename'
})
},
/*propertyNames: {
'evtStart': 'Start Time'
},*/
source: {
"Vehicle": 'Select Vehicle',
"Select Start Date": false,
"Select End Date": true
}
})]
Chrome developer tool output:
You returned json is not valid. It should be:
{"vehicles":[{"vehiclename":"pride"},{"vehiclename":"benz"}]}
(Quotation marks around the root vehicles).

Resources