Meteor Method.call issue in jquery-validation - javascript

I have a form to change password. I need to validate the old password. But jquery addMethod is always return false in Meteor.call. How to make it workable. Or is there any way? My bellow code will be more details about my issue.
$.validator.addMethod( 'checkPassword', ( oldpassword ) => {
var digest = Package.sha.SHA256(oldpassword);
Meteor.call('checkPassword', digest, function(err, result) {
var res = result.error != null; // even if this is "true", error message is visible.
return res;
});
});
$( "#changepassword" ).validate({
rules: {
oldpassword: {
required: true,
checkPassword: true
}
},
messages: {
oldpassword: {
required: "Please enter your Old Password",
checkPassword: "Password doesnt match!!!" //this message is visible all the time.
} }
});
Here is my method call
Meteor.methods({
checkPassword: function(digest){
if (Meteor.isServer) {
if (this.userId) {
var user = Meteor.user();
var password = {digest: digest, algorithm: 'sha-256'};
var result = Accounts._checkPassword(user, password);
return result;
}
}
}
});
here the meteor package

Related

(node:1572) UnhandledPromiseRejectionWarning: ValidationError: profile validation failed: education.0.fieldsofstudy: Path `fieldsofstudy` is required

I am trying to find the root cause of this validation error:(node:1572) UnhandledPromiseRejectionWarning: ValidationError: profile validation failed: education.0.fieldsofstudy: Path fieldsofstudy is required.
This is happening even I changed the "fieldsofstudy" to some other names, such as "majors". The same error message will still return.
Here is my profile code for education
// #route POST api/profile/education
// #desc Add education to profile
// #access Private
router.post(
"/education",
passport.authenticate("jwt", { session: false }),
(req, res) => {
const { errors, isValid } = validateEducationInput(req.body);
// Check Validation
if (!isValid) {
// Return any errors with 400 status
return res.status(400).json(errors);
}
Profile.findOne({ user: req.user.id }).then(profile => {
const newEdu = {
school: req.body.school,
degree: req.body.degree,
fieldofstudy: req.body.fieldofstudy,
from: req.body.from,
to: req.body.to,
current: req.body.current,
description: req.body.description
};
// Add to exp array
profile.education.unshift(newEdu);
profile.save().then(profile => res.json(profile));
});
}
);
Here is my code for the education tab
data.school = !isEmpty(data.school) ? data.school : "";
data.degree = !isEmpty(data.degree) ? data.degree : "";
data.fieldofstudy = !isEmpty(data.fieldofstudy) ? data.fieldofstudy:"";
data.from = !isEmpty(data.from) ? data.from : "";
if (Validator.isEmpty(data.school)) {
errors.school = "School field is required";
}
if (Validator.isEmpty(data.degree)) {
errors.degree = "Degree field is required";
}
if (Validator.isEmpty(data.fieldofstudy)) {
errors.fieldofstudy = "Field of study field is required";
}
if (Validator.isEmpty(data.from)) {
errors.from = "From date field is required";
}
return {
errors,
isValid: isEmpty(errors)
};
};
The problem is in your model. When you are creating your profile schema in your models folder, you have accidentally named it fieldsofstudy instead of fieldofstudy (singular). The fields in the validation has to match the fields in the model.

Forgot password Page

Good Afternoon every one,
I know this is very old question but I am very new to programming.Could any one help me
I have a forgot password page and it contains
Save button type is submit,Go to login link and one "User Name" of type input text.
Now when I click on save it should execute the following code
enter code here public VWUser ResetPassword(string userName)
{
using (var db = new AppDB())
{
var data = db.VWUsers.FirstOrDefault(m => m.UserName == userName && m.TenantId==Helper.TenantId);
if (data == null)
throw Helper.AppException(ExceptionTypes.Data, LocalText.ERR_UnAuthorizedAccess);
var password = SecurityManager.GenerateRandomPassword();
//data.Password = SecurityManager.Hash(password);
data.Password = SecurityManager.EncryptData(password);
db.SaveAndAssertChanges();
var result = db.VWUsers.First(x => x.UserName == data.UserName && x.TenantId ==Helper.TenantId);
result.xPassword = password;
return result;
}
}
And my Js will be like below
$(document).ready(function () {
debugger;
$("#frm-data").validate({
rules: {
UserName: {
required: true,
maxlength: 50,
},
},
showErrors: Helper.validateForm,
submitHandler: function (form) {
debugger;
Helper.httpPost("~/Login/ForgotPass",form, function (result) {
if (result.Status == 1) {
Helper.redirect("Login/Index");
}
else {
Helper.warning("Invalid Username or Password.");
// Helper.warning(result.Data);
}
})
}
});
})
can any one let me know how to do this.

Node js Unit testing method where fields of a model are not selected by default

Node js with mongoose.
model has fields that are not selected by default queries(select:false in model). In some scenarios I need to test the result to have the field selected. I have tried sinon-mongoose but it just tells me if a populate or select method was called, but for more flexibility I need to check the result data. And a requirement is not to use any real db connection, as it is a unit test.
The model
var DoctorSchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true
},
middleName: {
type: String
},
institutionName: {
type: String,
required: true,
select: false
}
});
The Service
module.exports = function (Doctor) {
service.getById = function(req, res, next){
Doctor.findOne({"_id" : req.params.id}).select('+institutionName').exec(function (err, doc) {
if (err) {
console.log(err);
return
};
if (!doc) {
res.send(404);
}
else {
res.json(doc);
}
});
}
}
So this can be tested
describe('doctorService getById', function () {
it('presentationService should call getById', function (done) {
var DoctorMock = sinon.mock(DoctorModel);
DoctorMock
.expects('findOne').withArgs({ "_id": "123" })
.chain("select").withArgs('+institutionName')
.chain('exec')
.yields(null, seed.doctor);
var serviceMock = doctorService(DoctorModel);
var res = {
json: function (data) {
DoctorMock.verify();
DoctorMock.restore();
assert.equal(seed.doctor, data, "Test fails due to unexpected result");
done();
}
};
serviceMock.getById({param:{id:"123"}}, res);
});
});
But in my example the test is bound to the chain. My intuition tells me that this is not a good approach.

JQuery Validate OR conditional [duplicate]

I have one field which can contain email or mobile (in my case mobile is 8 digits).
I already tried two approaches (both examples doesn't work, because 'element' do not have validate method):
First approach: create custom method and do both validations there, but then I have to create my own email and mobile validation - I couldn't find a way how to reuse jQuery validation rules in new methods. This is what I'd like to have:
jQuery.validator.addMethod("mobileoremail", function(value, element) {
return this.optional(element) ||
element.validate({ rules: { digits: true, rangelength: [8, 8] } }) ||
element.validate({ rules: { email: true } });
}, "Invalid mobile or email");
Second approach: create dependent rules. And also in this case I couldn't find a way how to reuse jQuery validation rules.
{ myRules: {
rules: {
user: {
required: true,
email: {
depends: function(element) {
return !element.validate({ rules: { mobile: true } });
}
},
mobile: {
depends: function (element) {
return !element.validate({ rules: { email: true } });
}
}
}
}
}
}
How about the following validation method...
$.validator.addMethod("xor", function(val, el, param) {
var valid = false;
// loop through sets of nested rules
for(var i = 0; i < param.length; ++i) {
var setResult = true;
// loop through nested rules in the set
for(var x in param[i]) {
var result = $.validator.methods[x].call(this, val, el, param[i][x]);
// If the input breaks one rule in a set we stop and move
// to the next set...
if(!result) {
setResult = false;
break;
}
}
// If the value passes for one set we stop with a true result
if(setResult == true) {
valid = true;
break;
}
}
// Return the validation result
return this.optional(el) || valid;
}, "The value entered is invalid");
Then we could set up the form validation as follows...
$("form").validate({
rules: {
input: {
xor: [{
digits: true,
rangelength: [8, 8]
}, {
email: true
}]
}
},
messages: {
input: {
xor: "Please enter a valid email or phone number"
}
}
});
See it in action here http://jsfiddle.net/eJdBa/

Add dynamic form validation callback to field

I am using formValidation.io and need to dynamically add a callback type validator within a class so that it can use a class property. The issue is that I initially pass my validator options into a super call that has some form validation procedures. But this means I do not have initial access to class properties.
So to do this I was trying to use updateOption but it definitely does not begin to validate this.
class MyForm extends Form {
var validatorOptions = {
fields: {
phoneNumber: {
validators: {
regexp: {
regexp: Regexp.phone,
message: "Please enter a valid phone number"
}
}
}
}
};
super({
validator: {
options: validatorOptions
}
});
var self = this;
this._cachedPhoneNumbers = [];
var phoneValidatorCallback = {
message: "This number is already in use",
callback: function(value, validator, $field) {
if ($.inArray(value, self._cachedPhoneNumbers) > -1)
return false;
return true;
}
}
// ref to validator is definitely valid!
this.validator.updateOption('phone', 'callback', 'callback', phoneValidatorCallback);
}
Here is the answer. I simply misused the function.
class MyForm extends Form {
var validatorOptions = {
fields: {
phoneNumber: {
validators: {
regexp: {
regexp: Regexp.phone,
message: "Please enter a valid phone number"
},
callback: {
message: 'This number is in use',
callback: function() {
return true;
}
}
}
}
}
};
super({
validator: {
options: validatorOptions
}
});
var self = this;
this._cachedPhoneNumbers = [];
function phoneValidatorCallback(value, validator, $field) {
if ($.inArray(value, self._cachedPhoneNumbers) > -1)
return false;
return true;
}
// ref to validator is definitely valid!
this.validator.updateOption('phone', 'callback', 'callback', phoneValidatorCallback);
}

Categories