I have a rate to validate only if delete =false. If not the validation is not required at all. I was trying below code, but it did not work. When delete = true, rate is NAN
charges: array().nullable().of(
object().shape({
rate: number().required().typeError("Rate missing")
.when("delete", {
is: true,
then: number().notRequired()
}
)
})
),
Maybe try to move 'number().when("delete", to rate: :
charges: array().nullable().of(
object().shape({
rate: number().when("delete", {
is: true,
then: number().notRequired(),
otherwise: number().required("Rate missing")
})
})
),
Related
We are using bookshelf.js with MySQL.
We have a Table: Contact(id, name, email_Id, updated_Contact_At)
bookshelf Query :
new Contact({id: 1}).save(
{name: 'Jhon Snow', email_Id: 'jhonsnow42#gmail.com', birthdate:'1998-10-21'},
{patch: true, default: false, require: true, method: 'update'}
);
which translates to :
Update Contact set name = "Jhon Snow",
email_Id = 'jhonsnow1212#gmail.com',
birthdate = '1998-10-21',
updated_Contact_At = 020-06-08T09:18:10.513Z
where id = 1;
after executing above query bookshelf fetches the same record:
select Contact.* from Contact where Contact.id = 1 limit 1
Is there any way in bookshelf.js to stop fetch call after updating record?
You can use autoRefresh = false while updating record
new Contact({id: 1}).save(
{name: 'Jhon Snow', email_Id: 'jhonsnow42#gmail.com', birthdate:'1998-10-21'},
{patch: true, default: false, require: true, method: 'update', autoRefresh : false}
);
use Bookshelf.js version: ^1.2.0
I know how to ask a user for his or her user name by a popup with Vue-SweetAlert2.
<template>
<v-btn class="create-button" color="yellow" #click="alertDisplay">Create</v-btn>
<br/>
<p>Test result of createCustomer: {{ createdCustomer }}</p>
</div>
</template>
<script>
export default {
data() {
return {
createdCustomer: null
}
},
methods: {
alertDisplay() {
var customer = await this.$swal({
title: 'What is your Name?',
input: 'text',
inputPlaceholder: 'Enter your name here',
showCloseButton: true,
});
console.log(customer);
this.createdCustomer = customer;
}
}
}
</script>
With code like the one above, you can store whatever the user typed into createdCustomer, and it should be displayed on the screen after the user gives the input.
But what if I wanted to ask the user for multiple pieces of information?
For example, how do I ask for info like
"customerNumber" (also want to make sure that alphabets and numbers are combined)
"locale" (also want to make sure that the input is a collection of choices that the user chooses from, like drop down menu, rather than a text field where you can type in whatever you like)
"firstName" (also want to make sure that the name doesn't exceed 255 characters)
etc.
in a single popup?
I tried to set multiple input fields like below, but I got a warning "Unknown parameter", and this doesn't seem to be a valid way.
var customer = await this.$swal({
title: 'Fill in your personal data',
input1: 'text',
input2: 'text',
input3: 'text',
inputPlaceholder: 'Enter your name here',
showCloseButton: true,
});
And how do I check if the user has given a valid input (like the name is within 255 characters, both of alphabets and numbers are used etc)?
If I were using C or Java, I could imagine using if-statements like
if(length <= 255){
// proceed
} else {
// warn the user that the input is too long
}
somewhere in the code, but in this case I don't know how I can do a similar if-statement like thing within the popup...
[ADDITIONAL QUESTION]
Is it also possible to pass an object that consists of multiple smaller elements, like "address"?
"address": {
"street": "string",
"city": "string",
"country": "USA",
"region": "string",
"zipCode": "string"
}
As per the documentation :
Multiple inputs aren't supported, you can achieve them by using html
and preConfirm parameters. Inside the preConfirm() function you can
return (or, if async, resolve with) the custom result:
const {value: formValues} = await Swal.fire({
title: 'Multiple inputs',
html: '<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
focusConfirm: false,
preConfirm: () => {
return [
document.getElementById('swal-input1').value,
document.getElementById('swal-input2').value
]
}
})
if (formValues) {
Swal.fire(JSON.stringify(formValues))
}
https://sweetalert2.github.io/
For validation you have to use the inputValidor prop like this :
const {value: ipAddress} = await Swal.fire({
title: 'Enter your IP address',
input: 'text',
inputValue: inputValue,
showCancelButton: true,
inputValidator: (value) => {
if (!value) {
return 'You need to write something!'
}
}
})
if (ipAddress) {
Swal.fire(`Your IP address is ${ipAddress}`)
}
I'm working on Ember JS and I have a weird problem which I found no solution for.
Now I have a form, in this form I have a 'cost' input which takes obviously
a cost of an item, right next to it is a select tag from which the user
selects the time spending for the entered cost.
If a user spend 10 dollars on the specified item everyday then he should select "Daily" from the select menu, if the 10 dollars are spent "Weekly"
the user should select "weekly" and so on and so forth.
Now beneath these two inputs I have four "readonly" tags in which I want to show the user how much he spends "daily" "weekly" "monthly" and "yearly".
But I get an error "Assertion Failed You Modified **** twice ..."
Here is my template:
{{ui-input value=name placeholder="Expense Name" label="Name"}}
{{ui-input value=cost placeholder="Expense Cost" label="Cost" half=true}}
{{ui-select value=costTime default="Expense Time" label="Expense Time" items=formData.expenseTime half=true}}
<div class="col-md-6 no-padding">
{{ui-readonly value=expense.daily placeholder="Daily" label="Daily" half=true}}
{{ui-readonly value=expense.weekly placeholder="Weekly" label="Weekly" half=true}}
</div>
<div class="col-md-6 no-padding">
{{ui-readonly value=expense.monthly placeholder="Monthly" label="Monthly" half=true}}
{{ui-readonly value=expense.yearly placeholder="Yearly" label="Yearly" half=true}}
</div>
and here is what I'm trying to do in my controller
import Ember from 'ember';
export default Ember.Component.extend({
expense : { daily: '', weekly: '', monthly: '', yearly: '' },
setExpense : Ember.computed('cost', 'costTime', 'expense.weekly', function() {
if (this.get('costTime') == 'daily') {
this.set('expense.weekly', Number(this.get('cost') * 7))
}
return this.get('expense.weekly')
}),
});
I can see that you are trying to set a property expense.weekly inside a computed property setExpense which is considered as an anti-pattern because setting a property inside a computed one may trigger a UI rerender and it's already deprecated. Moreover, from the logic inside the computed property (setExpense), I assume that it is perfectly fit for an action.
You can move the logic to a separate action and trigger it when the select option changes. This will eliminate the backtracking errors which you are facing now.
Alternative:
You can compute expense with the help of computed property with the appropriate dependent properties.
expense: Ember.computed('cost', 'costTime', function () {
let expense = { daily: '', weekly: '', monthly: '', yearly: '' };
// compute the expense here...
return expense;
})
Best pattern is to use DDAU and component didReceiveAttrs hook.
import Ember from 'ember';
export default Ember.Component.extend({
cost: null,
costTime: null
expense : { daily: '', weekly: '', monthly: '', yearly: '' },
didReceiveAttrs: function() {
var cost = this.get('cost');
var costTime = this.get('costTime');
if (cost && costTime) {
if (costTime == 'daily') {
this.set('expense.weekly', Number(cost * 7))
} else ...
}
}
});
and you must pass actions on change cost and costTime to parent component and change it there.
edit: Another approach is to define more properties:
import Ember from 'ember';
var multipliers = { daily: 1, weekly: 7, monthly: 30, yearly: 365 };
function computeDailyCost(cost, costTime) {
var multiplier = multipliers[costTime];
if (multiplier) {
return cost / multiplier
}
}
function defMultCost(multiplierKey) {
return Ember.computed("cost", "costTime", function() {
var dailyCost = this.computeDailyCost(this.get("cost"), this.get("costTime"));
var multiplier = multipliers[multiplierKey];
if (dailyCost != null && multiplier != null) {
return dailyCost * multiplier;
}
});
};
export default Ember.Component.extend({
cost: null,
costTime: null
daily: defMultCost("daily"),
weekly: defMultCost("weekly"),
monthly: defMultCost("monthly"),
yearly: defMultCost("yearly")
});
I did not test this, but it should work.
I need to set custom messages for text field in a form for pattern mismatch and empty field.
I have done all validation in backend but I also need to do this in front-end.
text_field:
<%= f.text_field :id_number, pattern: "[0-9]*", required: true, oninvalid: "this.setCustomValidity('Only numbers allowed')", oninput: "setCustomValidity('')" %>
The above one works fine on invalid pattern but, it also displays the same message 'Only numbers allowed' if the field is empty.
How can I set different messages for different errors that works in all type of browsers?
Anyone please help..
Thank you..
I am adding my answer - how to use the wonderful jquery.validate library for client side validation.
I am using version 1.13.1
Here it goes..
Download the library and place it in app/assets/javascripts/jqueryValidation/dist folder which includes additional-methods.min.js and jquery.validate.min.js.
Add the library in your asset pipeline so that its available globally.
//= require jqueryValidation/dist/jquery.validate
//= require jqueryValidation/dist/additional-methods
start using the library on the form in your _form.html.erb.
<%= form_for(#new,:html=>{:id=>"newForm") do |f |%>
//input fields with text/number/textarea etc
<%end%>
initialize the script and validate the form input fields.
$("form#new_form").validate({
//use this to ignore autocomplete fields present,if any
ignore: "",
//set rules for input elements using name attribute
rules: {
"new_form[address]": "required",
"new_form[tag]": "required",
"new_form[title]": {
required: true,
minlength: 3,
maxlength: 100
},
"new_form[contact_email]": {
required: true,
email: true,
minlength: 5,
maxlength: 100
},
"new_form_photos[avatar][]": {
required: true,
extension: "jpeg|jpg|png|gif"
},
//use this to show custom dedicated placeholder message everytime validation fails...just like dynamic alert
errorPlacement: function(error, element) {
$("#show_error").html("<span class='text-danger' >Fields marked with * are required</span>");
},
//use this callback to get which field is currently failing validation and then add more custom logic if needed
//for eg: you want to update the color of name label if validation fails.
//validator.errorList contains an array of objects, where each object has properties "element" and "message". element is the actual HTML Input.
invalidHandler: function(e,validator) {
//use the key value pair to get => id=new_form_title, to identify your input field
for (var i=0;i<validator.errorList.length;i++){
console.log(validator.errorList[i].element.attributes['id'].value);
if ( validator.errorList[0].element.attributes['id'].value == "new_form_tag"){
//handle tag input field here by adding css/alert/focus etc
}
}
}
});//validation ends
Similarly, we have submitHandler: function(form) {},onkeyup: function (element, event) {)
Hope it helps. :)
Giving you a very simple Example using Jquery for client-side validation. Try it:
Your form like, app/views/users/_form.html.erb
<%= form_for(#message=Message.new, :html => {:id => 'contact-form'}) do |f| %>
<div class="form-group">
<label for="phoneNo">Phone Number:</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">
<span class="glyphicon glyphicon-phone"> </span>
</span>
<%= f.text_field :contact, class: 'form-control' %>
</div>
</div>
In js file: app/assets/javascritps/users.js
$(document).on('ready page:load', function(){
$('#contact-form').validate({
rules:{
"message[contact]": {
required: true,
regex: /^[0-9]{10}$/
}
},
messages:{
"message[contact]":{
required: "Enter your contact number",
regex: "Enter valid contact number"
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("regex", function(value, element, regexpr) {
return regexpr.test(value);
}, "Enter valid number");
});
For client side validation you need to require jquery.validate.min(get it from https://jqueryvalidation.org/) in your js file. Then You can use form id to validate. Suppose your form id is #sliderForm and you want to validate textfield
<input id="slider_banner_title" name="slider_banner[title]" placeholder="Enter title" size="30" title="title" type="text" maxlength="255">
Then do like this:
$('#sliderForm').validate
rules:
"slider_banner[title]":
required: true
maxlength: 44
messages:
"slider_banner[title]":
required: "Title can't be blank"
maxlength: "Maximum 44 characters are allowed"
here slider_banner[title]" is name in input field.
I think the best way to define this in the model class. For an example if this input field is associated to an object related to the User model then, you define the following validations in the model,
validates :id_number, presence: {message: 'Id number required'}
validates :id_number, numericality: {message: 'Id number invalid data'}
Let me know if this works for you.
I want to get a specific value of drowpdown list using jquery and symfony
my code in formType given as follow
->add(
'predefinedMessage',
'entity',
array(
'empty_value' => 'Ajouter un message Prédéfini',
'class' => 'ACMBundle:Message',
'property' => 'name',
'multiple' => false,
'error_bubbling' => true,
'required' => false,
'query_builder' => function (EntityRepository $er) use ($user) {
return $er->createQueryBuilder('u')
->where('u.user = :user')
->setParameter('user', $user);
},
)
)
the entity Message has many fields: id, name, message, userid
I have a text area in my twig
{{ form_widget(form.message,{ 'attr': {'maxlength': '50','placeholder':'placeholder.message.message'|trans} }) }}
in my jquery
<script>
$('#add').click(function(){
var text="{{form.predefinedMessage.vars.data.message }}";
$('#Pushtype_message').val(text);
});
the value of message added to the text area, but when I select the other option, the value in the text area still the same.
consider I have an entity message which contain two line data
id:1 ,userid: 1 , name: message1, message: first message
id:2, userid: 2 , name:message2, message : second message