line up multiple objects having same data (reduce redundancy) - javascript

I am developing a web application and i have used jquery validation as :
$("#register").validate({
rules: {
emailID: {
required: true,
email: true
},
pass: {
required: true,
minlength: 6
},
user_email: {
required: true,
email: true
},
user_pass: {
required: true,
minlength: 6
}
}
everything is working but the problem is as object emailID and user_email both are having the same data also same for pass and user_pass, how can i line them in one without changing my name attribute in html, something like this :
$("#register").validate({
rules: {
emailID, user_email:
{
required: true,
email : true
}
}
i know this structure is not correct.
and as i am having lots of objects having same data, so it doesnt seems to be good doing the repetition

function RequiredRule( email, minlength ) {
this.email = email;
this.minlength = minlength;
this.required = true;
}
$("#register").validate({
rules: {
emailID: new RequiredRule(true),
pass: new RequiredRule(false, 6),
user_email: new RequiredRule(true),
user_pass: new RequiredRule(false, 6)
}
});

var one = {
required: true,
email: true
},
two = {
required: true,
minlength: 6
};
$("#register").validate({
rules: {
emailID: one,
pass: two,
user_email: one,
user_pass: two
}
});

Related

Mongoose Exclude document results at schema level

I am creating a model for my users. Each user has a property isVerified which is a boolean. I want to be able to call Model.find on the mongoose model and exclude all documents with isVerified === false without having to specify this during the query.
I want to set it in the schema such that whenever Model.find is called those documents are automatically excluded. Any help is appreciated
User model:
const UserSchema:Schema = new Schema({
name: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
index: true,
validate: {
validator: (value:string) => validator.isEmail(value),
message: (props:any) => "Invalid Email Address"
},
},
password: {
type: String,
trim: true,
required: true,
select: false,
minlength: 6,
validate: {
validator: (value:string) => !validator.contains(value, "password"),
message: (props:any) => "Your password cannot contain the word 'password'"
}
},
phoneNumber: {
type: String,
trim: true,
required: true,
validate: {
validator: (value:string) => validator.isMobilePhone(value, 'any', {strictMode: true}),
message: (props:any) => "Please include country code (e.g. +233 for Ghana +44 for the United Kingdom) to phone number"
}
},
isActive: {
type: Boolean,
default: false
}
,
tokens: [
{
token: {
type: String,
required: true
}
}
]
},{
strict: "throw",
timestamps: true
})
Edit:
I did some digging around and it appears I can overwrite the base methods to reimplement the query returned. I attempted to this is as seen below :
UserSchema.statics.find = function () {
let query = UserModel.find.apply(this, arguments);
query.where('isActive').ne(false)
return query;
}
However I obtain the following error
RangeError: Maximum call stack size exceeded
Finally figured it out. Needed to apply the change to the Model object and not the instance UserModel as seen below:
UserSchema.statics.find = function () {
let query = Model.find.apply(this, arguments);
query.where('isActive').ne(false)
return query;
}
Now the find method skips inactive users

minlength validator not working in mongoose

I have create schema in mongoose
let userSchema = new Schema({
name: {
type: String,
required: true,
lowercase: true,
trim: true,
minLength: 4,
maxLength: 15
}
});
when I update it with this query
user.updateOne(
{ "_id" : body.id },
{ $set: {
name:body.name,
phone:body.phone,
designation:body.designation,
address:body.address
} }
).then(function (updateDate) {
var data={message:"success",data:updateDate}
callback(data)
}).catch(function (err) {
var data={message:"error",data:err}
callback(data);
});
It does not throw any error if I update string with 2 length.
There are few solutions on stackoverflow but these are not working in my case
Firstly, in your schema minLength must be minlength, and maxLength must be maxlength with lowercase l.
So your schema must be like this:
let userSchema = new Schema({
name: {
type: String,
required: true,
lowercase: true,
trim: true,
minlength: 4,
maxlength: 15
}
});
Secondly, you need to add {runValidators: true} option to updateOne.
Update validators are off by default - you need to specify the
runValidators option.
So your code must be like this:
user.updateOne(
{ _id: body.id },
{
$set: {
name: body.name,
phone: body.phone,
designation: body.designation,
address: body.address
}
},
{ runValidators: true }
)
.then(function(updateDate) {
var data = { message: "success", data: updateDate };
callback(data);
})
.catch(function(err) {
var data = { message: "error", data: err };
callback(data);
});
You simple open mongodb Compass and then go to Validation option and change validation level to strict mode.

jquery form.validate conditional required

I am trying to get a form to validate based on information that was submitted. Everything works fine if I make all fields required but my validation does not work as soon as I put in an if statement on the requirement.
Does not work:
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: $('#email').val() ? false : true
},
email: {
required: $('#mobile').val() ? false : true
}
},
});
Works fine:
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: true
},
email: {
required: true
}
},
});
Thanks for the help!
I generally use depends and works in my case
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: {depends: function(element) {
return jQuery("#email").val() == '' ? true : false;
}
}
},
email: {
required: {depends: function(element) {
return jQuery("#mobile").val() == '' ? true : false;
}
}
}
}
});
I think you missed the order of email and mobile
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: $('#mobile').val() ? false : true
},
email: {
required: $('#email').val() ? false : true
}
},
});
I would recommend moving the conditional statement outside the validate object.
e.g.
var form = $("#send_request_sms");
var mobileRequired = $('#email').val() ? false : true;
var emailedRequired = $('#mobile').val() ? false : true;
form.validate({
rules: {
first_name: {
required: true
},
last_name: {
required: true
},
mobile: {
required: mobileRequired
},
email: {
required: emailRequired
}
}
});

errorPlacement can not be validate in first call but work fine in second click

using following function for validating but cant be work fine in first time but work fine in second time.
second function is used for validator and its not working fine when i first click the button but its work fine second time please help.
function saveValue(){
if (validateFormset().form()) { // validation perform
$('form#vendorActionForm').attr({methos: 'POST'});
$('form#vendorActionForm').attr({action: 'vendorAddressCreateUpdate.htm'});
$('form#vendorActionForm').submit();
}else{
$(".textMessgeClass").text("Please fill the highlighted field/s");
$(".textMessgeClass").addClass('errorClass');
$(".textMessgeClass").fadeIn("slow");
$(".textMessgeClass").delay(2000).fadeOut(2000);
}
}
function validateFormset(){
var validator = $("#vendorActionForm").validate({
rules: {
accountType: {
required:true
},
addressRank: {
required:true
},
street: {
required:true
},
city: {
required:true
},
state: {
required: true,
accept: "[a-zA-Z]+",
minlength: 2
},
region: {
required: true
},
zipCode: {
required: true,
rangelength: [3, 5]
},
contactName: {
required: true
},
mobile: {
required: false,
number: true,
minlength: 10
},
email: {
required: true,
email: true
},
email2: {
required: false,
email: true
},
email3: {
required: false,
email: true
}
},
errorPlacement: function(error, element) {
$(element).filter(':not(.valid)').addClass("addressErrorClass");
},
success: function(error) {
$("#vendorActionForm").find('.valid').removeClass("addressErrorClass");
}
});
alert('AAAA');
alert(validator);
return validator;
}

JS Validate - valid input & loagin bar while remote

I'm making a simple javascript form with validation. I've already planned my sintax and everything but I need help with two things:
I've templating my JS to output the error, but how can I change the inputbox color to "green" for example if the input is OK by validation?
My templating error until now:
$.validator.setDefaults(
{
showErrors: function(map, list)
{
this.currentElements.parents('label:first, .controls:first').find('.error').remove();
this.currentElements.parents('.control-group:first').removeClass('error');
$.each(list, function(index, error)
{
var ee = $(error.element);
var eep = ee.parents('label:first').length ? ee.parents('label:first') : ee.parents('.controls:first');
ee.parents('.control-group:first').addClass('error');
eep.find('.error').remove();
eep.append('<p class="error help-block"><span class="help-block error">' + error.message + '</span></p>');
});
//refreshScrollers();
}
});
Can you help me inserting the function to change the color if it's OK? I just can't figure it out.
Other thing is about showing a "loading" image while javascript is remotly checking if the user / email exists. I have everything ready and work, but I can't and don't know how to show a loading image while it checks ( before give error result ), neither tells the result is OK ( only in those fields ). My remote function:
$(function()
{
// validate signup form on keyup and submit
$("#registerform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 3,
remote:{
url: "inc/core/check_user.php",
type: "post",
data: {
username: function(){
return $( "#username" ).val();
}
}
}
},
password: {
required: true,
minlength: 5
},
confpassword: {
required: true,
minlength: 5,
equalTo: "#password"
},
scode: {
required: true,
minlength: 4,
maxlength: 6,
digits: true
},
scodeconf: {
required: true,
minlength: 4,
maxlength: 6,
digits: true,
equalTo: "#scode"
},
email: {
required: true,
email: true,
remote:{
url: "inc/core/check_email.php",
type: "post",
data: {
email: function(){
return $( "#email" ).val();
}
}
}
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required",
address: "required",
zipcode: "required",
city: "required",
state: "required",
country: "required",
data: "required",
age: "required"
},
messages: {
firstname: $lang['register_jquery_pnome'],
lastname: $lang['register_jquery_unome'],
username: {
required: $lang['register_jquery_username'],
minlength: $lang['register_jquery_username_min'],
remote: $lang['register_jquery_username_registado'],
},
password: {
required: $lang['register_jquery_password'],
minlength: $lang['register_jquery_password_min']
},
confpassword: {
required: $lang['register_jquery_password'],
minlength: $lang['register_jquery_password_min'],
equalTo: $lang['register_jquery_password_equalto']
},
email:{
required: $lang['register_jquery_email_valido'],
remote: $lang['register_jquery_email_registado']
},
agree: $lang['register_jquery_tos'],
address: $lang['register_jquery_morada'],
zipcode: $lang['register_jquery_zipcode'],
city: $lang['register_jquery_city'],
state: $lang['register_jquery_state'],
country: $lang['register_jquery_pais'],
data: $lang['register_jquery_data'],
age: $lang['register_jquery_age'],
scode: {
required: $lang['register_jquery_codigoseguranca'],
minlength: $lang['register_jquery_codigoseguranca_min'],
maxlenght: $lang['register_jquery_codigoseguranca_max'],
digits: $lang['register_jquery_codigoseguranca_digits']
},
scodeconf: {
required: $lang['register_jquery_codigoseguranca'],
minlength: $lang['register_jquery_codigoseguranca_min'],
maxlenght: $lang['register_jquery_codigoseguranca_max'],
digits: $lang['register_jquery_codigoseguranca_digits'],
equalTo: $lang['register_jquery_codigoseguranca_equalto']
},
}
});
});
Could someone help me with those two things? Thanks in advance!
For changing the color of valid elements you can add a class to them by adding the following to your validate function:
$("#registerform").validate({
validClass: "success",
// your code
});
Then style your success class: .success {background-color: green}
The remote option is just a normal jQuery.ajax() call so you can use all the same settings.
Should be something like this:
remote:{
url: "inc/core/check_user.php",
beforeSend: function( xhr ) {
//your code to show a message
},
type: "post",
data: {
username: function(){
return $( "#username" ).val();
}
},
complete: function() {
// your code to hide the message
}
}

Categories