Angular 5 Validators.pattern('(0\d{1}|1[0-2])\\/([0-2]\d{1}|3[0-1])\\/(19|20)\d{2}') Not working - regex

the input field always showing error, could some one help me.
var dateRegEx = /^(0\d{1}|1[0-2])\/([0-2]\d{1}|3[0-1])\/(19|20)\d{2}$/;
hiredate: new FormControl({value:null}, Validators.compose([Validators.required,Validators.pattern(dateRegEx)])),
This is also not working.
Update: I used the control with mat-datepicker, which setting the control value automatically to javascript date if we input default mm dd yyyy format otherwise it is setting null.
<mat-form-field>
<input matInput id="hiredate" name="hiredate" required [matDatepicker]="picker1" placeholder="Hire Date" formControlName="hiredate">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
<mat-error *ngIf="isFieldInvalid('hiredate')">
Please provide Hire Date
</mat-error>
</mat-form-field>
Please check my answer.

After debugging I found that, the underlaying mat-datepicker automatically setting the input value to Date value, and it accepts the default format as mm[-/. ]dd[-/. ]]yyyy if the user inputs in this format, it sets control value as Date value, which is not validated with date pattern. if the user provides in different pattern input, it sets control value as NULL.
import {Injectable} from "#angular/core";
import {FormControl} from "#angular/forms";
#Injectable()
export class DateValidator {
constructor() {
}
static date(c: FormControl) {
//const dateRegEx = new RegExp(/^(0\d|1[0-2])\/([0-2]\d|3[0-1])\/(19|20)\d{2}$/);
//console.log('Date Value is:',c.value);
return c.value!=null ? null : {
dateValidator: {
valid: false
}
};
}
}
and the control defined with validator as
hiredate: new FormControl({value:null}, Validators.compose([Validators.required,DateValidator.date])),
and now the validator working fine with mat-datepicker

Related

vue testing vuetify input for disabled

I am very new to testing and I'm struggling my way through all this new stuff I am learning. Today I want to write a test for a vuetify <v-text-field> component like this:
<v-text-field
v-model="user.caption"
label="Name"
:disabled="!checkPermissionFor('users.write')"
required
/>
my test should handle the following case:
an active, logged in user has a array in vuex store which has his permissions as a array of strings. exactly like this
userRights: ['dashboard', 'imprint', 'dataPrivacy']
the checkPermissionFor() function is doing nothing else then checking the array above with a arr.includes('x')
after it came out the right is not included it gives me a negotiated return which handles the disabled state on that input field.
I want to test this exact scenario.
my test at the moment looks like this:
it('user has no rights to edit other user overview data', () => {
const store = new Vuex.Store({
state: {
ActiveUser: {
userData: {
isLoggedIn: true,
isAdmin: false,
userRights: ['dashboard', 'imprint', 'dataPrivacy']
}
}
}
})
const wrapper = shallowMount(Overview, {
store,
localVue
})
const addUserPermission = wrapper.vm.checkPermissionFor('users.write')
const inputName = wrapper.find(
'HOW TO SELECT A INPUT LIKE THIS? DO I HAVE TO ADD A CLASS FOR IT?'
)
expect(addUserPermission).toBe(false)
expect(inputName.props('disabled')).toBe(false)
})
big questions now:
how can I select a input from vuetify which has no class like in my case
how can I test for "is the input disabled?"
wrapper.find method accepts a query string. You can pass a query string like this :
input[label='Name'] or if you know the exact index you can use this CSS query too : input:nth-of-type(2).
Then find method will return you another wrapper. Wrapper has a property named element which returns the underlying native element.
So you can check if input disabled like this :
const buttonWrapper = wrapper.find("input[label='Name']");
const isDisabled = buttonWrapper.element.disabled === true;
expect(isDisabled ).toBe(true)
For question 1 it's a good idea to put extra datasets into your component template that are used just for testing so you can extract that element - the most common convention is data-testid="test-id".
The reason you should do this instead of relying on the classes and ids and positional selectors or anything like that is because those selectors are likely to change in a way that shouldn't break your test - if in the future you change css frameworks or change an id for some reason, your tests will break even though your component is still working.
If you're (understandably) worried about polluting your markup with all these data-testid attributes, you can use a webpack plugin like https://github.com/emensch/vue-remove-attributes to strip them out of your dev builds. Here's how I use that with laravel mix:
const createAttributeRemover = require('vue-remove-attributes');
if (mix.inProduction()) {
mix.options({
vue: {
compilerOptions: {
modules: [
createAttributeRemover('data-testid')
]
}
}
})
}
as for your second question I don't know I was googling the same thing and I landed here!

Show Current Date Time in field in alpaca automatically

I am using alpaca framework. I have date time type, when I click on it only I can able to select the DateTime, I want this to be filled automatically with current date time when it gets focus or when page loaded.
Any suggestions please.
You can use the "data" object in alpaca config to set the date field default value to current date:
"data": { "myDateField": new Date() // or you can use moment } }
You can also set the date in the postRender function like this:
"postRender": function(control) {
var date = control.childrenByPropertyId["date"];
var currentDateTime = moment().format("MM/DD/YYYY HH:mm:ss")
date.setValue(currentDateTime);
}
Here's a working fiddle for that.

How to make Date Editable while using Glass mapper

Today i am facing one issue which has following requirement.
Date should be Editable.
Date should be in particular format.
My Code is like below which is not working.
foreach(var item in Model)
{
<div>#Editable(item, x => x.Start_Date.ToString("MMMM dd,yyyy"))</div>
}
I have tried following approach but throwing "DateParameters" namespace error.
#Editable(item, x=> x.Start_Date, new DateParameters { Format = "MMMM dd,yyyy"})
Also i have learner following thing but how can i achieve this ?
To make a field editable takes two parameters, this has been used to make the Date field editable. The first parameter instructs Glass.Mapper which field to make editable, the second parameter then specifies what the output should be when the page is not in page editing mode. This allows you to control the output of the field when in the two different modes.
Can anybody help me ?
For Experience editor mode, this works for me in razor view:
#Editable(model => model.SomeDateField, new { Format = "dd-MM-yyyy" })
Sitecore 8.2 though, with Glass 4.4.
What you want to do is to provide the default format but keep things the same for the main glass stuff. Like so:
foreach(var item in Model)
{
<div>#Editable(item, x => x.Start_Date, x=>x.Start_Date.ToString("MMMM dd,yyyy"))</div>
}
This will make the date a normal date when editing, but allow you to format it for the final page.
Usually in this case i use different code for "Normal View" and "Experience Editor", so for normal view you need only to display the date with format without making it editable, and on experience editor you need only to edit the date field the author will not care about the date format with experience editor, so your code will be like this :
foreach(var item in Model)
{
{
#if (Sitecore.Context.PageMode.IsExperienceEditorEditing)
{
<div>#Editable(item, x => x.Start_Date)</div>
}
else
{
<div>#item.Start_Date.ToString("MMMM dd,yyyy")</div>
}
}
}
I have tried that as well but it is throwing an error like below
**Value cannot be null. Parameter name: objectToSwitchTo
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.Common.Switcher2.Enter(TValue objectToSwitchTo)
at Glass.Mapper.Sc.GlassHtml.MakeEditable[T](Expression1 field, Expression1 standardOutput, T model, Object parameters, Context context, Database database, TextWriter writer)**
Any help on this ?

ember pick-a-date how to pull value?

There is a pick-a-date add-on for Ember found here.
{{pick-a-date date=(readonly date) on-selected=(action (mut date)) placeholder="Pick a date" options=(readonly extraPickadateOptions)}}
How would I pass a saved date value to the tag? The below (value=date) does not seem to work?
{{pick-a-date value=date date=(readonly date) on-selected=(action (mut date)) placeholder="Pick a date" options=(readonly extraPickadateOptions)}}
Or what if I wanted to change the value from 'date' to something different... for example dob... so it would 'mimic' this
{{input value=dob}}
I have also tried using this addon and faced same issue. I need date in timestamp format and I implemented like following. You can check this,
{{pikaday-input
value=inputDateValue
onSelection=(action 'setSelectedDate') }}
For getting the value and binding that to object, I added following code in action handler,
actions : {
setSelectedDate : function (date) {
//To get the timestamp in seconds
let timestamp = Math.floor(date.getTime() / 1000);
this.set("inputDateValue", date);
// Used timestamp for setting value to object
record.set("dateTime", timestamp);
}
}
For setting the value I used folowing code,
if(record.get("dateTime") {
let date = record.get("dateTime") * 1000;
let dateValue = new Date(date);
this.set("inputDateValue", dateValue);
}

record not added to model when i call save() on a new record in Ember-Data

Using Ember-Data 0.13-59 & Ember 1.0.0 RC 6 (from starter kit)
Problem: upon save() to a new record made from App.Userstat.createRecord({ ... }) the server gets the POST and successfully returns an id but the new record is not available in the Userstat model.
To better understand example: this is a quiz app(for multiple choice questions). Each question has several choices and when a user selects a choice, their choice to the corresponding question is stored in a Model, App.Userstat.
At each question, the app needs to know whether the user has already answered this question or if it's new.
I use a computed property as a setter and getter. The setter is called when a user selects a choice (the choice's value is passed to computed property). First it checks if a record exists for the user's current question. If it doesn't exist it will create a new record. If it does exist, it should only issue a PUT request with updated content.
Code Updated(July 8, 11AM)
App.UserstatsController = Ember.ArrayController.extend();
App.QuestionController = Ember.ObjectController.extend({
needs: "userstats",
chosen = function(key, value) {
// getter
if(value === undefined) {
// something goes here
// setter
} else {
// the question.id is used to compare for an existing record in Userstat mdoel
var questionId = this.get('id');
var questionModel = this.get('model');
// does any Userstat record belong to the current question??
var stats = this.get('controllers.Userstats');
var stat = stats.get('model').findProperty('question.id', questionId);
// if no record exists for stat, means user has not answered this question yet...
if(!stat) {
newStat = App.Userstat.createRecord({
"question" : questionModel,
"choice" : value // value passed to the computed property
)}
newStat.save(); // I've tried this
// newStat.get('store').commit(); // and this
return value;
// if there is a record(stat) then we will just update the user's choice
} else {
stat.set('choice', value);
stat.get('store').commit();
return value;
}
}.property('controllers.Userstats')
No matter how many times I set chosen it always sends a POST (as opposed to an update only sending a PUT request) because it never adds the record to the model the first time.
To demonstrate further, in the setter part of the computed property, when I put this code:
var stats = this.get('controllers.Userstats')
console.log stats
the Userstats controller shows all previously existing records, but not newly submitted records!
How come the new record isn't available after I save() or commit() it???
Thanks :)
EDIT
maybe it has something to do with me adding a record to the singular model App.Userstat and then when I look for it, I'm searching using the UserstatsController which is an Array controller???
I don't know if it's a typo, but the computed property is defined the wrong way and should be like this:
App.QuestionController = Ember.ObjectController.extend({
needs: 'userstats',
choice: 'controllers.userstats.choice',
chosen: function(key, value) {
...
}.property('choice')
...
});
Inside the property() you should also define properties that trigger the computed property if they change. This way if choice changes the chosen cp will be triggered.
Please let me know if it helps.