Reset form and validation - forms

I have a problem with a dialog modal who don,t want to close even with a function
I have this code to reset and close the modal, the resetting is ok but nothing close with cancel, I use the resetForm() function
I have a form with this structure ( form and rules )
<template>
<div class="text-center">
<v-dialog
v-model="dialog"
>
<template v-slot:activator="{ on }">
<v-btn class="addGroup" v-on="on">Add a group</v-btn>
</template>
<v-form
ref="form"
v-model="valid"
lazy-validation
>
<v-card>
<v-card-title
class="headline grey lighten-2"
primary-title
>
Add a group
</v-card-title>
<v-stepper v-model="e1">
<v-stepper-header class="stepHeader">
<v-stepper-step :complete="e1 > 1" step="1">Choose a name</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 2" step="2">Select fixtures</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 3" step="3">Apply a recipe</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 4" step="4" >Select dates</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step step="5">Summary</v-stepper-step>
</v-stepper-header>
<v-stepper-items>
<v-stepper-content step="1" class="mt-6">
<v-card
>
<div class="step chooseName">
<h3>Create a group</h3>
<p class="mt-12">Choose a name for your group</p>
<v-text-field
:rules="rules.name"
#keyup.enter="e1 = 2"
v-model="form.groupName"
></v-text-field>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 2"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="2" class="mt-6">
<v-card
>
<div class="step selectFixtures">
<h3><v-icon #click="e1 = 1">mdi-chevron-left</v-icon>Select fixtures</h3>
<p class="mt-12 mb-6"
>Choose fixtures you want associate with {{form.groupName}}.</p>
<v-select
:rules="rules.fixture"
v-model="form.selectedFixture"
:items="fixtures"
item-text="name"
></v-select>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 3"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="3" class="mt-6">
<v-card
flat
height="68vh"
rounded
>
<div class="step applyRecipe">
<h3><v-icon #click="e1 = 2">mdi-chevron-left</v-icon>Apply a recipe to your group</h3>
<p class="mt-12 mb-6">Select a recipe for the group {{groupName}}.</p>
<div class="selectRecipe">
<v-select
class="mr-6"
v-model="form.selectedRecipe"
:items="recipe"
item-text="name"
item-value="duration"
return-object>
</v-select>
<p>or</p>
<create_recipe></create_recipe>
</div>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 4"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="4" class="mt-6">
<v-card
>
<div class="selectDates">
<h3><v-icon #click="e1 = 3">mdi-chevron-left</v-icon>Select start date</h3>
<p class="mt-6">Select the launch date of the Tuscan sun recipe for the {{groupName}} group</p>
<p>The end date will be set automatically according to the parameters of your recipe</p>
<v-date-picker
class="mt-6 ml-6"
v-model="selectedDate"
no-title
:date-format="date => new Date(date).toDateString()"
>
</v-date-picker>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 5"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="5" class="mt-6">
<v-card
>
<div class="stepChooseName">
<h3><v-icon #click="e1 = 4">mdi-chevron-left</v-icon>Summary</h3>
<p class="answer">Group name :</p>
<p class="subtitle">{{form.groupName}}</p>
<v-divider></v-divider>
</div>
</v-card>
<v-btn
#click="submit()"
>
Add group
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
</v-stepper-items>
</v-stepper>
</v-card>
</v-form>
</v-dialog>
</div>
</template>
I have this code to reset and close the modal, the resetting is ok but nothing close with cancel, I use the resetForm() function
I have a form with this structure ( form and rules )
<script>
import Create_recipe from "./create_recipe";
export default {
components: {Create_recipe},
props: ['groups', 'fixtures'],
groups: [],
data() {
const defaultForm = Object.freeze({
groupName: '',
selectedFixture: [],
selectedRecipe: '',
selectedScenario: '',
});
return {
form: Object.assign({}, defaultForm),
valid: true,
rules: {
name: [val => (val || '').length > 0 || 'This field is required'],
fixture: [val => (val || '').length > 0 || 'fixture is required'],
recipe: [val => (val || '').length > 0 || 'recipe is required'],
},
dialog: null,
defaultForm,
e1:0,
counterOfUnnamed:'',
checkbox: true,
fixtures: this.fixtures,
selectedDate: new Date().toISOString().substr(0, 10),
recipe: [{
id:1,
name: 'Tuscan sun',
duration: '5',
},
{ id:2,
name: 'Montreal summer',
duration: '10',
},
{ id:3,
name: 'French spring',
duration: '365',
}
],
}
},
methods: {
numberOfFixture() {
return this.form.selectedFixture.length;
},
resetForm () {
this.$refs.form.reset();
this.dialog = false
},
submit() {
if (!this.form.groupName) {
this.form.groupName = "Unnamed" + this.counterOfUnnamed;
this.counterOfUnnamed = this.counterOfUnnamed + 1;
this.counterOfUnnamed = parseInt(this.counterOfUnnamed);
}
var self = this;
http.post('group/create', {
name: self.form.groupName,
}).then((result) => {
self.groups.push(result);
self.resetForm();
})
},
},
computed: {
displayFixturesName() {
return this.form.selectedFixture.join(', ');
},
formIsValid() {
return (
this.form.selectedFixture &&
this.form.selectedRecipe
)
}
}
}
</script>
```
But when I launch the reset function, the form is reset but the validation appears.
How can I solve it ?

In your case use this.$refs.form.resetValidation() for reset the validation after reset
resetForm () {
this.$refs.form.reset()
this.$refs.form.resetValidation()
},
Here is the working code
Codepen link: https://codepen.io/chansv/pen/QWWExBz?editors=1010
<div id="app">
<v-app id="inspire">
<v-form
ref="form"
v-model="valid"
>
<v-text-field
v-model="formObj.name"
:counter="10"
:rules="nameRules"
label="Name"
required
></v-text-field>
<v-text-field
v-model="formObj.email"
:rules="emailRules"
label="E-mail"
required
></v-text-field>
<v-btn
:disabled="!valid"
color="success"
class="mr-4"
#click="submitForm"
>
Submit
</v-btn>
<v-btn
color="error"
class="mr-4"
#click="reset"
>
Reset Form
</v-btn>
</v-form>
</v-app>
</div>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data() {
const defaultForm = Object.freeze({
name: '',
email: '',
})
return {
formObj: Object.assign({}, defaultForm),
valid: true,
nameRules: [
v => !!v || 'Name is required',
v => (v && v.length <= 10) || 'Name must be less than 10 characters',
],
emailRules: [
v => !!v || 'E-mail is required',
v => /.+#.+\..+/.test(v) || 'E-mail must be valid',
],
};
},
methods: {
submitForm () {
console.log(this.formObj);
},
reset () {
this.$refs.form.reset();
console.log(this.formObj);
},
},
})
If you are reseting the form , no need to set default value this.form = Object.assign({}, this.defaultForm)
This reset function automatically resets all the value in the form this.$refs.form.reset()

Related

Resetting validation in vue

here's the example of my simple form which throws an error when the text field is empty. On the first submit everything is ok, but after next you see the error before submitting second message. Here's code:
<div id="app">
<v-app >
<v-dialog v-model="dialog">
<template v-slot:activator="{ on }">
<v-btn v-on="on">Open</v-btn>
</template>
<v-card>
<v-text-field
v-model="note"
:rules="noteRules"
></v-text-field>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn #click="submit()">save</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-app>
</div>
and app.js
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
dialog: false,
note: '',
noteRules: [
v => !!v || 'error'
],
}),
methods: {
clear() {
this.dialog = false;
//something here?
}
}
})
how should I reset the validation? here's codepen https://codepen.io/tutu-kaen/pen/oNjPPKe
Wrap your content of the card in a v-form, add a v-model and a ref to that v-form.
You can then access that v-form in your clear() by using this.$refs..
The formValid will be a boolean so you can easily check if a form is valid by using if (this.formValid) anywhere in your code, for example to disable the send button.
Example:
<div id="app">
<v-app>
<v-dialog v-model="dialog">
<template v-slot:activator="{ on }">
<v-btn v-on="on">Open</v-btn>
</template>
<v-card>
<v-form v-model="formValid" ref="myForm">
<v-text-field v-model="note" :rules="noteRules"></v-text-field>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn #click="submit()">save</v-btn>
</v-card-actions>
</v-form>
</v-card>
</v-dialog>
</v-app>
</div>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
dialog: false,
note: '',
formValid: false,
noteRules: [
v => !!v || 'error'
],
}),
methods: {
submit() {
this.note = '';
this.dialog = false;
this.$refs.myForm.reset();
}
}
})
Codepen example

Dialog modal not closing

I have a problem with a dialog modal who don,t want to close even with a function
I have this code to reset and close the modal, the resetting is ok but nothing close with cancel, I use the resetForm() function
I have a form with this structure ( form and rules )
<template>
<div class="text-center">
<v-dialog
v-model="dialog"
>
<template v-slot:activator="{ on }">
<v-btn class="addGroup" v-on="on">Add a group</v-btn>
</template>
<v-form
ref="form"
v-model="valid"
lazy-validation
>
<v-card>
<v-card-title
class="headline grey lighten-2"
primary-title
>
Add a group
</v-card-title>
<v-stepper v-model="e1">
<v-stepper-header class="stepHeader">
<v-stepper-step :complete="e1 > 1" step="1">Choose a name</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 2" step="2">Select fixtures</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 3" step="3">Apply a recipe</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 4" step="4" >Select dates</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step step="5">Summary</v-stepper-step>
</v-stepper-header>
<v-stepper-items>
<v-stepper-content step="1" class="mt-6">
<v-card
>
<div class="step chooseName">
<h3>Create a group</h3>
<p class="mt-12">Choose a name for your group</p>
<v-text-field
:rules="rules.name"
#keyup.enter="e1 = 2"
v-model="form.groupName"
></v-text-field>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 2"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="2" class="mt-6">
<v-card
>
<div class="step selectFixtures">
<h3><v-icon #click="e1 = 1">mdi-chevron-left</v-icon>Select fixtures</h3>
<p class="mt-12 mb-6"
>Choose fixtures you want associate with {{form.groupName}}.</p>
<v-select
:rules="rules.fixture"
v-model="form.selectedFixture"
:items="fixtures"
item-text="name"
></v-select>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 3"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="3" class="mt-6">
<v-card
flat
height="68vh"
rounded
>
<div class="step applyRecipe">
<h3><v-icon #click="e1 = 2">mdi-chevron-left</v-icon>Apply a recipe to your group</h3>
<p class="mt-12 mb-6">Select a recipe for the group {{groupName}}.</p>
<div class="selectRecipe">
<v-select
class="mr-6"
v-model="form.selectedRecipe"
:items="recipe"
item-text="name"
item-value="duration"
return-object>
</v-select>
<p>or</p>
<create_recipe></create_recipe>
</div>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 4"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="4" class="mt-6">
<v-card
>
<div class="selectDates">
<h3><v-icon #click="e1 = 3">mdi-chevron-left</v-icon>Select start date</h3>
<p class="mt-6">Select the launch date of the Tuscan sun recipe for the {{groupName}} group</p>
<p>The end date will be set automatically according to the parameters of your recipe</p>
<v-date-picker
class="mt-6 ml-6"
v-model="selectedDate"
no-title
:date-format="date => new Date(date).toDateString()"
>
</v-date-picker>
</div>
</v-card>
<v-btn
color="primary"
#click="e1 = 5"
>
Continue
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
<v-stepper-content step="5" class="mt-6">
<v-card
>
<div class="stepChooseName">
<h3><v-icon #click="e1 = 4">mdi-chevron-left</v-icon>Summary</h3>
<p class="answer">Group name :</p>
<p class="subtitle">{{form.groupName}}</p>
<v-divider></v-divider>
</div>
</v-card>
<v-btn
#click="submit()"
>
Add group
</v-btn>
<v-btn
text
#click="dialog = !dialog"
>
Cancel</v-btn>
</v-stepper-content>
</v-stepper-items>
</v-stepper>
</v-card>
</v-form>
</v-dialog>
</div>
</template>
I have this code to reset and close the modal, the resetting is ok but nothing close with cancel, I use the resetForm() function
I have a form with this structure ( form and rules )
<script>
import Create_recipe from "./create_recipe";
export default {
components: {Create_recipe},
props: ['groups', 'fixtures'],
groups: [],
data() {
const defaultForm = Object.freeze({
groupName: '',
selectedFixture: [],
selectedRecipe: '',
selectedScenario: '',
});
return {
form: Object.assign({}, defaultForm),
valid: true,
rules: {
name: [val => (val || '').length > 0 || 'This field is required'],
fixture: [val => (val || '').length > 0 || 'fixture is required'],
recipe: [val => (val || '').length > 0 || 'recipe is required'],
},
dialog: null,
defaultForm,
e1:0,
counterOfUnnamed:'',
checkbox: true,
fixtures: this.fixtures,
selectedDate: new Date().toISOString().substr(0, 10),
recipe: [{
id:1,
name: 'Tuscan sun',
duration: '5',
},
{ id:2,
name: 'Montreal summer',
duration: '10',
},
{ id:3,
name: 'French spring',
duration: '365',
}
],
}
},
methods: {
numberOfFixture() {
return this.form.selectedFixture.length;
},
resetForm () {
this.$refs.form.reset();
this.dialog = false
},
submit() {
if (!this.form.groupName) {
this.form.groupName = "Unnamed" + this.counterOfUnnamed;
this.counterOfUnnamed = this.counterOfUnnamed + 1;
this.counterOfUnnamed = parseInt(this.counterOfUnnamed);
}
var self = this;
http.post('group/create', {
name: self.form.groupName,
}).then((result) => {
self.groups.push(result);
self.resetForm();
})
},
},
computed: {
displayFixturesName() {
return this.form.selectedFixture.join(', ');
},
formIsValid() {
return (
this.form.selectedFixture &&
this.form.selectedRecipe
)
}
}
}
</script>
```
But when I launch the reset function, the form is reset but the validation appears.
How can I solve it ?
There is a bug in above code, check in console, "this" keyword in Vue js should not use inside fat array functions. By default the current context points to main Vue instance in any Vue components, methods and computed properties. Using this will change the reference. In this code, it gets struck when you are calling this.groups.push(result)
Better preserve the this reference and try to achieve the same by putting resetForm inside then block
submit() {
var self = this;
http.post('group/create', {
name: self.form.groupName,
}).then((result) => {
self.groups.push(result)
self.resetForm();
// still you face issue add this line here "self.dialog = false;"
})
.catch(err => {
// handle error
});
},
Your updated script:
<script>
import Create_recipe from "./create_recipe";
const defaultForm = Object.freeze({
groupName: '',
selectedFixture: [],
selectedRecipe: '',
selectedScenario: '',
});
export default {
components: {Create_recipe},
props: ['groups', 'fixtures'],
groups: [],
data() {
return {
form: Object.assign({}, defaultForm),
valid: true,
rules: {
name: [val => (val || '').length > 0 || 'This field is required'],
fixture: [val => (val || '').length > 0 || 'fixture is required'],
recipe: [val => (val || '').length > 0 || 'recipe is required'],
},
dialog: null,
defaultForm,
e1:0,
counterOfUnnamed:'',
checkbox: true,
fixtures: this.fixtures,
selectedDate: new Date().toISOString().substr(0, 10),
recipe: [{
id:1,
name: 'Tuscan sun',
duration: '5',
},
{ id:2,
name: 'Montreal summer',
duration: '10',
},
{ id:3,
name: 'French spring',
duration: '365',
}
],
}
},
methods: {
numberOfFixture() {
return this.form.selectedFixture.length;
},
resetForm () {
this.$refs.form.reset();
this.dialog = false
},
submit() {
if (!this.form.groupName) {
this.form.groupName = "Unnamed" + this.counterOfUnnamed;
this.counterOfUnnamed = this.counterOfUnnamed + 1;
this.counterOfUnnamed = parseInt(this.counterOfUnnamed);
}
var self = this;
http.post('group/create', {
name: self.form.groupName,
}).then((result) => {
self.groups.push(result);
self.form = Object.assign({}, defaultForm);
self.dialog = false;
})
},
},
computed: {
displayFixturesName() {
return this.form.selectedFixture.join(', ');
},
formIsValid() {
return (
this.form.selectedFixture &&
this.form.selectedRecipe
)
}
}
}
</script>

Semantic UI Custom Rule Validation for Select Drop-Down Field

I am trying to add some custom logic to my semantic ui validation but can't figure out what I am doing wrong.
Basically, when the user selects "Yes" from the drop-down, I would like to make the "input_field" mandatory. If the user selects "No", the "input_field" becomes optional and the form can be submitted.
I tried searching for examples and followed some code from the Semantic Ui website but can't figure out what I am missing. Any advice would be appreciated as I am on a deadline for a project I am working on.
Form:
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
Validation:
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
},
input_field: {
identifier: 'input_field',
depends: 'select',
rules: [
{
type: 'empty',
prompt: function() {
$('.select').on('change', function() {
if( this.value == 'Yes') {
return "Custom Validation";
}
return false;
}).trigger("change");
}
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
});
</script>
Figured out a solution for this! It might not be the best answer but it works and does what I am looking for.
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
$('.selectOption').on('change', function() {
if ( this.value == 'Yes' ) {
$('.ui.form').form('add rule', 'input_field', ['empty', 'integer']);
$('.ui.form').form('add prompt', 'input_field', 'Enter an integer');
}
if ( this.value == 'No' ) {
$('.ui.form').form('remove prompt', 'input_field');
$('.ui.form').form('remove rule', 'input_field');
}
}).trigger("change");
});
</script>
I was able to implement the validation rule by extending Semantic UI setting rules.
See below example:
$.fn.form.settings.rules.dependsOnFieldValue = function (value, dependFieldValue) {
var identifier = dependFieldValue.split('[')[0];
var dependValue = dependFieldValue.match(/\[(.*)\]/i)[1];
if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
matchingValue = $('[data-validate="'+ identifier +'"]').val();
}
else if($('#' + identifier).length > 0) {
matchingValue = $('#' + identifier).val();
}
else if($('[name="' + identifier +'"]').length > 0) {
matchingValue = $('[name="' + identifier + '"]').val();
}
else if( $('[name="' + identifier +'[]"]').length > 0 ) {
matchingValue = $('[name="' + identifier +'[]"]');
}
return (matchingValue !== undefined)
? !( dependValue.toString() === matchingValue.toString() && value === '')
: false
;
};
Then in the form validation initializer you will pass the desired values as below:
$(".ui.form").form({
fields: {
select: {
identifier: 'select',
rules : [
{
type : 'empty'
}
]
},
input_field: {
identifier : 'input_field',
rules : [
{
type : 'dependsOnFieldValue[select[Yes]]',
}
]
},
...
}
});
Notice that we pass the <select> identifier (in this case also called select) within the first [] and then the value that we want to see to make the input_field mandatory ("Yes" in this case).

Algolia - DateTimePicker - Select Date

I would like to implement a date timepicker with Algolia. If I choose a date, all elements should be displayed from this date.
Unfortunately, I have no idea how I can make this with Agolia.
I hope you can help me.
const datePicker = instantsearch.connectors.connectRange(
(options, isFirstRendering) => {
if (!isFirstRendering) return;
new Calendar({
element: $('.daterange--single'),
current_date: new Date(),
format: {input: 'DD.MM.YYYY'},
required: false,
callback: function() {
const start = new Date().getTime();
refine([start]);
},
});
}
);
search.addWidget(
datePicker({
attributeName: 'date',
})
);
<div class="daterange daterange--single"></div>
now i have a working code. Now a have the problem.. how i can change in my custom widget the searchParameters?
const search = instantsearch({
appId: '0000000',
apiKey: '000000000000',
indexName: 'Events',
routing: true,
searchParameters:{
filters: 'dateNumeric >= 1531591200'
}
});
var customWidget = {
init: function(options) {
$( "#datetimepickerNotime" ).focusout(function() {
var date = $('#datefromdatetimepicker').val();
var date = new Date (date);
alert("dateNumeric >= 1512752400");
});
}
};
search.addWidget(customWidget);
<div class='input-group date' id="datetimepickerNotime">
<input type='text' id="datefromdatetimepicker" name="date" class="form-control" autocomplete="off" value="<f:format.date date='now' format='d.m.Y' />"/>
<span class="input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
import { Formik, Field } from 'formik';
import { connectRange } from 'react-instantsearch-dom';
import * as Yup from 'yup';
const RangeFilter = ({ currentRefinement, min, max, refine }) => {
const validationSchema = Yup.object().shape({
minValue: Yup.number().min(min, `Minimum value must be at least ${min}`),
maxValue: Yup.number().max(max, `Maximum value must be at most ${max}`),
});
const onSubmit = (values) => {
refine({ min: values.minValue, max: values.maxValue });
};
return (
<Formik
onSubmit={onSubmit}
validationSchema={validationSchema}
initialValues={{
minValue: currentRefinement?.min,
maxValue: currentRefinement?.max,
}}>
{({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field name="minValue">
{({ field, form: { errors, touched } }) => (
<div>
<label htmlFor="price-min">To price:</label>
<input
className="input is-shadowless"
{...field}
id="price-min"
type="number"
placeholder="Min price"
/>
{errors.minValue && touched.minValue && (
<p className="help is-danger">{errors.minValue}</p>
)}
</div>
)}
</Field>
<Field name="maxValue">
{({ field, form: { errors, touched } }) => (
<div className="mt-2">
<label htmlFor="price-max">From price:</label>
<input
{...field}
id="price-max"
type="number"
className="input is-shadowless"
placeholder="Max price"
/>
{errors.maxValue && touched.maxValue && (
<p className="help is-danger">{errors.maxValue}</p>
)}
</div>
)}
</Field>
<button type="submit" className="ais-RefinementList-showMore mt-2">
Get Result
</button>
</form>
)}
</Formik>
);
};
export default connectRange(RangeFilter);

angular4 form saving exception

hi every body i am using angular 4 , when i save form in deployment mode, i get the error down , and when i save the same form in development mode i don't get the exception.
my form code products-form.component.ts :
import {Component, OnInit, OnDestroy, ViewChild, ElementRef} from '#angular/core';
import {NgForm} from '#angular/forms';
import {AdminService} from "../../../services/admin.service";
import {HttpService} from "../../../../http.service";
import {Subscription} from "rxjs";
import {Http, Response, Headers,RequestOptions} from "#angular/http";
import {ActivatedRoute, Router} from "#angular/router";
import { trigger, state, style, transition, animate } from '#angular/animations';
import {BrowserAnimationsModule} from '#angular/platform-browser/animations';
import {BusyModule} from 'angular2-busy';
import { FormGroup, FormBuilder, Validators,ReactiveFormsModule } from '#angular/forms';
import { BrowserModule } from '#angular/platform-browser';
import {MdDialog, MdDialogRef} from '#angular/material';
import {DiscardPopUpComponent} from '../../../../discard-pop-up/discard-pop-up.component';
#Component({
selector: 'app-products-form',
templateUrl: './products-form.component.html',
styleUrls: ['./products-form.component.css']
})
export class ProductsFormComponent implements OnInit, OnDestroy {
product:any = {'needTransformer':'Yes',
'power':'',
'cct':'',
'cri':'',
'lightSource':'',
'country':'',
'category':{},
'productionCompany':{},
'finish':{}};
discardPopUpTitle:string = "Discard Changes";
discardPopUpContent:string="Are you Sure you want to discard changes and exit to products table ?";
selectedPopUpOption:string;
discardDialog:DiscardPopUpComponent;
showPopUp = false;
popUpresult = false;
isFormDirty:boolean=false;
companies: string[] =[];
companiesSubscription: Subscription;
finishes: string[] = [];
finishesSubscription: Subscription;
categories: string[] = [];
categoriesSubscription: Subscription;
lightSources: string[] = [];
lightSourcesSubscription: Subscription;
countries: string[] = [];
countriesSubscription: Subscription;
routeSubscritpion: Subscription;
selectedCategory: string;
selectedFinish: string;
selectedProductionCompany: string;
selectedLightSource: string;
selectedCountry: string;
selectedTransformerNeeded: string;
isEdit: boolean = false;
isShow: boolean = false;
message: string;
#ViewChild('mainImage') mainImage: ElementRef;
#ViewChild('diemsnions') diemsnions: ElementRef;
#ViewChild('effects') effects: ElementRef;
#ViewChild('pdf') pdf: ElementRef;
#ViewChild('categoryEl') categoryEl: ElementRef;
busy: any;
isSuccess: boolean = false;
currentCode: string;
constructor(private httpService:HttpService, private adminService: AdminService, private http: Http, private route: ActivatedRoute, private router: Router,public dialog: MdDialog) {
console.log(dialog);
this.discardDialog = new DiscardPopUpComponent();
}
ngOnInit() {
// this.busy = true;
this.routeSubscritpion = this.route.params.subscribe(param => {
let code = param['code'];
if(code != undefined)
this.httpService.getProductDataByCode(code).subscribe(
(data:any)=> {
this.product=data;
this.currentCode = data.code;
this.isEdit = true;
this.selectedCategory = data.category.name;
this.selectedFinish = data.finish.name;
this.selectedCountry = data.country;
this.selectedProductionCompany = data.productionCompany.name;
this.selectedLightSource = data.lightSource;
this.selectedTransformerNeeded = data.transformerNeeded;
// this.categoryEl.nativeElement.value = data.category.name;
},
(err) => console.error(err+"<-------------"),
() => console.log('Random Quote Complete')
);
});
this.companiesSubscription = this.httpService.getAllCompanies().subscribe(
(data:any)=> {
data.forEach((entry)=> {
this.companies.push(entry.name);
});
if(this.companies.length > 0)
this.product.productionCompany = this.companies[0];
},
(err) => console.error(err+"<-------------"),
() => console.log('Random Quote Complete')
);
this.categoriesSubscription = this.httpService.getAllCategories().subscribe(
(data:any)=> {
data.forEach((entry)=> {
this.categories.push(entry.name);
});
if(this.categories.length > 0)
this.product.category = this.categories[0];
},
(err) => console.error(err+"<-------------"),
() => console.log('Random Quote Complete')
);
this.finishesSubscription = this.httpService.getAllFinishes().subscribe(
(data:any)=> {
data.forEach((entry)=> {
this.finishes.push(entry.name);
});
if(this.finishes.length > 0)
this.product.finish = this.finishes[0];
},
(err) => console.error(err+"<-------------"),
() => console.log('Random Quote Complete')
);
this.lightSourcesSubscription = this.httpService.getAllLightSources().subscribe(
(data:any)=> {
this.lightSources = data;
if(this.lightSources.length > 0)
this.product.lightSource = this.lightSources[0];
},
(err) => console.error(err+"<-------------"),
() => console.log('Random Quote Complete')
);
this.httpService.getAllCountries().subscribe(
(data:any)=> {
this.countries = data;
if(this.countries.length > 0)
this.product.country = this.countries[0];
},
(err) => console.error(err+"<-------------"),
() => console.log('Random Quote Complete')
);
}
readUrl(event,url) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event) => {
var target:FileReader=<FileReader>event.target;
this.product[url] = target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
}
formatStrings(str)
{
str=str.replace(/\s/g, '');
str=str.replace(/,/g, '');
str=str.toUpperCase();
return str
}
onSubmit(form:NgForm)
{
var values=form.value;
let parent=this;
let obj={
name:values.name,
description:values.description,
code:values.code,
category:{
name:values.categories
},
productionCompany:{
name:values.productionCompany
},
finish:{
name:values.finish
},
transformerNeeded:values.transformerNeeded,
power:values.power,
cct:values.cct,
cri:values.cri,
ik: values.ik,
ip: values.ip,
luminous: values.luminous,
optic: values.optic,
lightSource:values.lightSource,
country:values.productionContry,
effictImagePath:'',
normalImagePath:'',
detailsImagePath:'',
catalogPath:''
};
let headers = new Headers({ 'Content-Type': 'application/json' ,'Authorization': JSON.parse(localStorage.getItem('currentUser'))['token']});
let options = new RequestOptions({ headers: headers });
if(!this.isEdit) {
this.busy = this.http.post('http://levelskw.com/products/', JSON.stringify(obj), options).subscribe(
(data: any) => {
this.product=obj;
this.currentCode = obj.code;
this.isEdit = true;
this.selectedCategory = obj.category.name;
this.selectedFinish = obj.finish.name;
this.selectedCountry = obj.country;
this.selectedProductionCompany = obj.productionCompany.name;
this.selectedLightSource = obj.lightSource;
this.selectedTransformerNeeded = obj.transformerNeeded;
this.isSuccess = true;
this.message="Success";
parent.upload(obj.code)
},
(err) => {
this.isSuccess = false;
this.message=JSON.parse(err._body).msg;
this.isShow = true;
let timeoutId = setTimeout(() => {
this.isShow = false;
}, 5000);
},
() => console.log("")
);
} else {
this.busy = this.http.put('http://levelskw.com/products/'+this.currentCode, JSON.stringify(obj), options).subscribe(
(data: any) => {
this.isSuccess = true;
this.message="Success";
parent.upload(this.currentCode);
},
(err) =>{
this.isSuccess = false;
this.message=JSON.parse(err._body).msg;
this.isShow = true;
let timeoutId = setTimeout(() => {
this.isShow = false;
}, 5000);
},
() => console.log("")
);
}
console.log(JSON.stringify(obj));
}
ngOnDestroy() {
this.isFormDirty = false;
this.companiesSubscription.unsubscribe();
this.finishesSubscription.unsubscribe();
this.lightSourcesSubscription.unsubscribe();
}
changeFinish(finish) {
this.product.finish = finish;
console.log(this.product);
}
makeFileRequest(url:string) {
return new Promise((resolve, reject) => {
let mainImageEl: HTMLInputElement = this.mainImage.nativeElement;
let formData = new FormData();
let xhr = new XMLHttpRequest();
if (mainImageEl.files.length > 0)
formData.append("normalImagePath", mainImageEl.files.item(0), mainImageEl.files.item(0).name);
let diemsnionsEl: HTMLInputElement = this.diemsnions.nativeElement;
if (diemsnionsEl.files.length > 0)
formData.append("detailsImagePath", diemsnionsEl.files.item(0), diemsnionsEl.files.item(0).name);
let effectsEl: HTMLInputElement = this.effects.nativeElement;
if (effectsEl.files.length > 0)
formData.append("effictImagePath", effectsEl.files.item(0), effectsEl.files.item(0).name);
let pdfEl: HTMLInputElement = this.pdf.nativeElement;
if (pdfEl.files.length > 0)
formData.append("catalogPath", pdfEl.files.item(0), pdfEl.files.item(0).name);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Authorization", JSON.parse(localStorage.getItem('currentUser'))['token']);
xhr.send(formData);
});
}
upload(code: string) {
this.busy = this.makeFileRequest("http://levelskw.com/products/upload/"+code).then((result) => {
this.isShow = true;
let timeoutId = setTimeout(() => {
this.isShow = false;
}, 5000);
}, (error) => {
this.isShow = true;
let timeoutId = setTimeout(() => {
this.isShow = false;
}, 5000);
});
}
cancel() {
this.router.navigate(['/admin/products']);
}
openDialog() {
this.showPopUp=true;
this.discardDialog.show();
}
takePopUpEvent(isPopUpValueConfermed:boolean){
this.popUpresult = isPopUpValueConfermed;
if(this.popUpresult){
this.cancel() ;
}else{
this.showPopUp=false;
}
}
onChange(form:NgForm){
console.log(form);
this.isFormDirty = true;
}
}
my HTML code products-form.component.html :
<app-popup [isShow]="isShow" [message]="message" [isSuccess]="isSuccess"></app-popup>
<div [ngBusy]="busy"></div>
<div class="main-container">
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<app-discard-pop-up [showPopUp]="showPopUp" [popUpTitle]="discardPopUpTitle" [popUpContent]="discardPopUpContent" (isConfermed)="takePopUpEvent($event)" ></app-discard-pop-up>
<div fxLayout="column" fxLayoutGap="15px">
<div fxLayout="row" fxLayoutGap="29px">
<div fxLayout="column" fxLayoutGap="20px">
<div fxLayout="column" class='titleSection'>
<div class="header"><div class='header-label'>Header</div></div>
<div class='title'><input type="text" placeholder="Code" name="code" [(ngModel)]="product.code" (ngModelChange)="onChange(f)" /></div>
<div class='title'><input type="text" placeholder="Name" name="name" [(ngModel)]="product.name" (ngModelChange)="onChange(f)" /></div>
<div class="description"><textarea placeholder="Description" name="description" [(ngModel)]="product.description" (ngModelChange)="onChange(f)" ></textarea></div>
</div>
<div fxLayout="column" class="loadSection">
<div class="header"><div class='header-label'>Files</div></div>
<div fxLayout="column" class="img-section" fxLayoutGap="2px">
<div class="img-lable">Main image</div>
<div class="img-btn">
<button fxLayoutAlign="center center">Upload</button>
<img class="img-view" [src]="product.normalImagePath" />
<input type="file" (change)="readUrl($event,'normalImagePath')" #mainImage (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column" class="img-section" fxLayoutGap="2px">
<div class="img-lable">Dimensions</div>
<div class="img-btn">
<button fxLayoutAlign="center center">Upload</button>
<img class="img-view" [src]="product.detailsImagePath" />
<input type="file" (change)="readUrl($event,'detailsImagePath')" #diemsnions (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column" class="img-section" fxLayoutGap="2px">
<div class="img-lable">Effects</div>
<div class="img-btn">
<button fxLayoutAlign="center center">Upload</button>
<img class="img-view" [src]="product.effictImagePath" />
<input type="file" (change)="readUrl($event,'effictImagePath')" #effects (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column" class="img-section" fxLayoutGap="2px">
<div class="img-lable">PDF</div>
<div class="img-btn">
<button fxLayoutAlign="center center">Upload</button>
<img class="img-view" src="../../../../assets/Icons/pdf.png" />
<input type="file" #pdf (ngModelChange)="onChange(f)" />
</div>
</div>
</div>
</div>
<div fxLayout="column" class="details" fxLayoutGap="10px">
<div class="header"><div class='header-label'>Related Products</div></div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Category</div>
<select class="dropdown" name="categories" [(ngModel)]="selectedCategory" (ngModelChange)="onChange(f)" >
<option *ngFor="let category of categories" [ngValue]="category">{{category}}</option>
</select>
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Manufactured By</div>
<select class="dropdown" name="productionCompany" [(ngModel)]="selectedProductionCompany" (ngModelChange)="onChange(f)" >
<option *ngFor="let company of companies" [ngValue]="company">{{company}}</option>
</select>
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Materials</div>
<select class="dropdown" name="finish" [(ngModel)]="selectedFinish" (ngModelChange)="onChange(f)" >
<option *ngFor="let finish of finishes" [ngValue]="finish">{{finish}}</option>
</select>
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Transformer needed</div>
<select class="dropdown" name="transformerNeeded" [(ngModel)]="selectedTransformerNeeded" (ngModelChange)="onChange(f)" >
<option value="true" selected>Yes</option>
<option value="false" >No</option>
</select>
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Power(W)</div>
<input type="number" name="power" [(ngModel)]="product.power" (ngModelChange)="onChange(f)"/>
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>CCT(K)</div>
<div fxLayout="row">
<input type="number" name="cct" [(ngModel)]="product.cct" #cct="ngModel" number (ngModelChange)="onChange(f)" />
<div class="validation-error-message"> <p *ngIf="cct.errors?.number" color:red> CCT should be number</p></div>
</div>
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>IK</div>
<input type="number" name="ik" [(ngModel)]="product.ik" (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Index of protection</div>
<input type="number" name="ip" [(ngModel)]="product.ip" (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Luminous</div>
<input type="number" name="luminous" [(ngModel)]="product.luminous" (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Optic</div>
<input type="number" name="optic" [(ngModel)]="product.optic" (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>CRI</div>
<input type="number" name="cri" [(ngModel)]="product.cri" (ngModelChange)="onChange(f)" />
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Light Source</div>
<select class="dropdown" name="lightSource" [(ngModel)]="selectedLightSource" (ngModelChange)="onChange(f)" >
<option *ngFor="let lightSource of lightSources" [ngValue]="formatStrings(lightSource)" >{{lightSource}}</option>
</select>
</div>
</div>
<div fxLayout="column">
<div class="item-cont">
<div class='lable'>Production country</div>
<select class="dropdown" name="productionContry" [(ngModel)]="selectedCountry" (ngModelChange)="onChange(f)" >
<option *ngFor="let company of countries" [ngValue]="formatStrings(company)" >{{company}}</option>
</select>
</div>
</div>
</div>
</div>
<div class='control-btn-container'>
<div fxLayout="row" fxLayoutGap="10px">
<button class="btn cancel" fxLayoutAlign="center center" (click)="cancel()">Cancel</button>
<button type="submit" class="btn save" fxLayoutAlign="center center" >Save</button>
</div>
</div>
</div>
</form>
</div>
i use spring boot in the backend.
ERROR Error: Uncaught (in promise): Error: Runtime compiler is not loaded
Error: Runtime compiler is not loaded
at y (vendor.600ff6e….bundle.js:781)
at Z (vendor.600ff6e….bundle.js:218)
at t.compileModuleAndAllComponentsAsync (vendor.600ff6e….bundle.js:365)
at vendor.600ff6e….bundle.js:521
at t.invoke (vendor.600ff6e….bundle.js:781)
at Object.onInvoke (vendor.600ff6e….bundle.js:365)
at t.invoke (vendor.600ff6e….bundle.js:781)
at e.run (vendor.600ff6e….bundle.js:781)
at vendor.600ff6e….bundle.js:781
at t.invokeTask (vendor.600ff6e….bundle.js:781)
at Object.onInvokeTask (vendor.600ff6e….bundle.js:365)
at t.invokeTask (vendor.600ff6e….bundle.js:781)
at e.runTask (vendor.600ff6e….bundle.js:781)
at s (vendor.600ff6e….bundle.js:781)
at HTMLFormElement.invoke (vendor.600ff6e….bundle.js:781)
at y (vendor.600ff6e….bundle.js:781)
at Z (vendor.600ff6e….bundle.js:218)
at t.compileModuleAndAllComponentsAsync (vendor.600ff6e….bundle.js:365)
at vendor.600ff6e….bundle.js:521
at t.invoke (vendor.600ff6e….bundle.js:781)
at Object.onInvoke (vendor.600ff6e….bundle.js:365)
at t.invoke (vendor.600ff6e….bundle.js:781)
at e.run (vendor.600ff6e….bundle.js:781)
at vendor.600ff6e….bundle.js:781
at t.invokeTask (vendor.600ff6e….bundle.js:781)
at Object.onInvokeTask (vendor.600ff6e….bundle.js:365)
at t.invokeTask (vendor.600ff6e….bundle.js:781)
at e.runTask (vendor.600ff6e….bundle.js:781)
at s (vendor.600ff6e….bundle.js:781)
at HTMLFormElement.invoke (vendor.600ff6e….bundle.js:781)
at y (vendor.600ff6e….bundle.js:781)
at p (vendor.600ff6e….bundle.js:781)
at vendor.600ff6e….bundle.js:781
at t.invokeTask (vendor.600ff6e….bundle.js:781)
at Object.onInvokeTask (vendor.600ff6e….bundle.js:365)
at t.invokeTask (vendor.600ff6e….bundle.js:781)
at e.runTask (vendor.600ff6e….bundle.js:781)
at s (vendor.600ff6e….bundle.js:781)
at HTMLFormElement.invoke (vendor.600ff6e….bundle.js:781)