Angular 5 form Invalid never 'False' - angular5

The only thing I changed about this form code was adding a validator for the password match and now the variable invalid is never false.
Form Setup:
this.CreateUserForm = new FormGroup({
Email: new FormControl(null, Validators.required), // Create Email validator!
Password: new FormControl(null, Validators.required),
ConfirmPassword: new FormControl(null, Validators.required),
FirstName: new FormControl(null, Validators.required),
LastName: new FormControl(null, Validators.required),
MiddleInitial: new FormControl(null) // Write custom validators for single character, upper case, letters only
}, PasswordValidation.MatchPassword);
Password Match:
import { AbstractControl } from '#angular/forms';
export class PasswordValidation
{
static MatchPassword(AC: AbstractControl)
{
var data = AC.value;
let password = AC.get('Password'); // to get value in input tag
let confirmPassword = AC.get('ConfirmPassword'); // to get value in input tag
if (password.value != confirmPassword.value)
{
AC.get('ConfirmPassword').setErrors({ MatchPassword: true })
} else
{
AC.get('ConfirmPassword').setErrors({});
return null;
}
}
}

in case of valid don't setErros, just return null.
if (password.value != confirmPassword.value)
{
AC.get('ConfirmPassword').setErrors({ MatchPassword: true })
} else
{
// AC.get('ConfirmPassword').setErrors({});
return null;
}

Related

In Angular 14 how to add nonNullable to Form Control which has validations

form: FormGroup;
createMyForm() {
this.form = new FormGroup<any>({
firstName: new FormControl<any>('', [Validators.required]),
lastName: new FormControl<any>('', { nonNullable: true }),
});
}
How to add { nonNullable: true } to firstName
I am trying to add {nonNullable: true } to the form control.
lastName: new FormControl('', { nonNullable: true }),
I am able to add {nonNullable: true } to the control which doesnt have validations, but for the form control which has validations I am not able to add {nonNullable: true }.
firstName: new FormControl('', [Validators.required]),
createMyForm() {
this.form = new FormGroup<any>({
firstName: new FormControl<any>('', {
nonNullable: true,
validators: [Validators.required]
}),
lastName: new FormControl<any>('', { nonNullable: true })
});
}
if all fields has nonNullable:true and you are comfortable injecting form-builder, you can use NonNullableFormBuilder

How to destruct a complex object

One of my functions returns the object below:
Promise {
{
user: {
name: 'Ervin Howell',
email: 'Shanna#melissa.tv',
type: 'authenticated'
}
}
}
How to destruct user object from this json?
hi you can read the JSON API in this site. it has two methods:JSON.parse and JSON.sringify.
for your situation, you can use JSON.parse if your function return a JSON string
let json = "{
user: {
name: 'Ervin Howell',
email: 'Shanna#melissa.tv',
type: 'authenticated'
}
}
}"
obj = JSON.parse(json);
// when you want the user object
let user = obj.user
// when you want the user's name
let name = user.name

Find document by ID and push another subdocument

I have two Collection schemas, and I want to insert one Model instance of one schema (FA) inside an array field of the other Model schema (FP):
var FASchema = new Schema({
Timestamp: Date,
PrognostizierterBetriebswert: Number,
posFlexPot: Number,
negFlexPot: Number,
Leistungsuntergrenze: Number,
Leistungsobergrenze: Number,
posGesEnergie: Number,
negGesEnergie: Number,
Preissignal: Number,
Dummy1: Schema.Types.Mixed,
Dummy2: Schema.Types.Mixed,
Dummy3: Schema.Types.Mixed
//same: Dummy: {}
});
module.exports = mongoose.model("FA", FASchema, 'FA');
and
var FPSchema = new Schema( {
_id: String, //mongoose.Schema.Types.ObjectId,
Demonstrator: Number,
erstellt: {type: Date, 'default': Date.now},
von: Date,
bis: Date,
Fahrplanabschnitte: { type: Schema.Types.ObjectId, ref: 'FA' },
})
module.exports = mongoose.model("FP", FPSchema, 'FP');
Now, whenever I create a new FA document, I want to push the FA document into my FP collection inside the array "Fahrplanabschnitte". Either by a reference, or by a schema/nested subdocument... What is the best way to do it and how can I do it?
I call the POST method that should do the job with: router.route('/FA/FPPUT/:FP_id').put(FAController.create_and_push_to_FP_by_ID)
The function itself looks like this:
In a first step, a FA instance is created and saved in FA Collection, then the FP collection is updated and into the array "Fahrplanabschnitte", the new FA instance should be inserted. However, it does not work as planned..
exports.create_and_push_to_FP_by_ID=function(req,res) {
console.log(req.body)
var fa = new FA(req.body);
//SAVE the new instance
fa.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("Instanz FA in Datenbank erzeugt!");
res.status(200);
res.json({ message: 'FA-Instance created in datbase!' })
}
});
FP.findOneAndUpdate({_id: req.params.FP_id}, function(err, fp) {
if (err){
res.send(fa);
}
//res.json(fp);
fp.Fahrplanabschnitte.push(fa._id);
})
};
What am I doing wrong?
You are going wrong here
`fp.Fahrplanabschnitte.push(fa._id); //does't make sense at all`
above line doesn't do or update anything to the mongodb database...
you need to use $push operator to update the collection in the
database
exports.create_and_push_to_FP_by_ID=function(req,res) {
console.log(req.body)
var fa = new FA(req.body);
//SAVE the new instance
fa.save(function(err, fa) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("Instanz FA in Datenbank erzeugt!");
FP.findOneAndUpdate({_id: req.params.FP_id}, { $push: {
Fahrplanabschnitte: fa._id } } function(err, fp) {
if (err){
return res.send(fa);
}
res.status(200);
res.json({ message: 'FA-Instance created in datbase!' })
})
}
});
};

How to avoid duplicate entries in IBM JSONStore

WL.JSONStore.get(collectionName).change(data, options) method does not seem to work for duplicate values. I get duplicate values entered whenever data is loaded through the adapter. Below is the code that I have used to avoid duplicate entries.
init(){
console.log('JSONStore init function callled');
let collections = {
activities: {
searchField: {serialKey: 'string'},
adapter: {
name: 'ServiceAdapter',
add: 'pushActivities',
remove: 'removeActivity',
replace: 'replaceActivity',
load: {
procedure: 'getActivities',
params: [],
key: 'rows'
}
}
}
}
WL.JSONStore.init(collections).then((success) => {
console.log('-->JSONStore init success')
}, (failure) => {
console.log('-->JSONStore init failed', failure)
})
}
load() {
let dataRequest = new
WLResourceRequest("/adapters/ServiceAdapter/getActivities",
WLResourceRequest.GET);
dataRequest.send().then(
(response) => {
this.data = response.responseJSON.rows;
this.activityService.put(this.data);
})
}
put(data){
console.log('--> JSONStore put function called');
let collectionName = 'activities';
let options = {
replaceCriteria: ['serialKey'],
addNew: true,
markDirty: false
};
WL.JSONStore.get(collectionName).change(data, options).then((success) => {
console.log('--> JSONStore put success')
}, (failure) => {
console.log('--> JSONStore put failed', failure)
})
}
Adapter Function:
function getActivities() {
var path = 'employees' + '/_all_docs?include_docs=true';
var input = {
method : 'get',
returnedContentType : 'json',
path : path,
};
var response = MFP.Server.invokeHttp(input);
if (!response.rows) {
response.isSuccessful = false;
return response;
} else {
var results = [];
for (var i=0; i < response.rows.length; i++) {
results.push(response.rows[i].doc);
}
return {'rows': results};
}
}
I have even tried by:
searchFields: {serialKey: 'string',serialId: 'string'}
replaceCriteria: ['serialKey','serialId']
But no luck.
NOTE: There is no error in the former one, whereas the later results in an error.
ERROR : PROVISION_TABLE_SEARCH_FIELDS_MISMATCH (I have already tried to destroy the collection and perform the change, as the link suggests.
I have followed the below link:
https://www.youtube.com/watch?v=Ep6w1zXoI-k
I am using the below versions:
mfpdev : 8.0.0-2017102406
Let me know if you need any more details.

Bind validation results from ajax request to form model in mithril

Hi I would like to bind html inputs with validation response model returned from API like that:
{"userName":[{"memberNames":["UserName"],"errorMessage":"Field User Name is required."}],"acceptTerms":[{"memberNames":["AcceptTerms"],"errorMessage":"Accepting terms is requried"}]}
And my component in mithril
var RegisterPage = {
vm: {
userName: m.prop(),
password: m.prop(),
confirmPassword: m.prop(),
acceptTerms: m.prop(false)
},
controller: function (args) {
this.title = 'Register new user account';
this.vm = RegisterPage.vm;
this.register = function (e) {
e.preventDefault();
apiRequest({ method: "POST", url: "http://localhost:12116/auth/register", data: RegisterPage.vm }).then(RegisterPage.vm.registerResult)
}
},
view: function (ctrl, args) {
return m('form.input-group',
[
m('.input-row', [m('label', 'Email'), m('input[type=email][placeholder=Your email address like myemail#email.com]', { onchange: m.withAttr("value", ctrl.vm.email) })]),
m('.input-row', [m('label', 'Password'), m('input[type=password][placeholder=your password]', { onchange: m.withAttr("value", ctrl.vm.password) })]),
m('.input-row', [m('label', 'Confirm password'), m('input[type=password][placeholder=your password]', { onchange: m.withAttr("value", ctrl.vm.confirmPassword) })]),
m('.input-row', [m('label', 'Accept terms and conditions'), m('input[type=checkbox]', { onchange: m.withAttr("checked", ctrl.vm.acceptTerms) })]),
m('button[type=submit].btn btn-positive btn-block', { onclick: ctrl.register }, 'Register account')
]);
}
}
I am looking for some generic solution. I would like to mark invalid fields with css class and add field validation message.
UPDATE
In my project I use some wrapper around m.request to get more details when 400 is thrown
function apiRequest(args) {
NProgress.start();
if (!args.unwrapError) {
args.unwrapError = function (data, xhr) {
if (xhr.status === 401)
{
layout.badRequestMsg(xhr.statusText);
}
NProgress.done();
return data;
}
}
if (!args.unwrapSuccess) {
args.unwrapSuccess = function (data, xhr) {
NProgress.done();
return data;
}
}
return m.request(args);
}