I use the following code to validate URL in client side. My question is if there is a better way to do the same..My question is not about the regex that i am using (just the overall way of writing)
this.validators.myUrl = function(value) {
if (!_.isUndefined(value) && !_.isNull(value)) {
if ($.trim(value).length == 0) {
return {
isValid: true
}
} else {
return /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test($.trim(value)) == true ? {
isValid: true
} : {
isValid: false,
message: "Enter a valid URL"
};
}
} else {
if ($.trim(value).length == 0) {
return {
isValid: true
}
}
}
};
Why you don't want to use ready plugins/libraries?
You can have used jQuery Validation Plugin and its url method.
All what you need is:
$( "#myform" ).validate({
rules: {
field: {
required: true,
url: true
}
}
});
where myform is id of your form.
Related
I want to update v-model value by code and validate that field. So I am using vue.set method for updating value and then call $validator.validate.
my code is something like that.
Vue.set(model,property, value);
vm.$validator.validate(property).then(function (valid) {
if (!valid) {
vm.$validator.flag(property, {
touched: true,
dirty: true
});
}
});
my validation rules code is somethng like that:
Validator.extend("val_compulsory", {
getMessage(field, args) {
return args[0];
},
validate(value) {
return {
valid: !!value,
data: {
required: true
}
};
}
}, { computesRequired: true });
but in val_compulsory validator I always get previous value which is before vue.set. Is there any way to get latest value in vee-validator validation methods after vue.set?
Try this:
Vue.set(model,property, value);
vm.$nextTick(function() {
vm.$validator.validate(property).then(function (valid) {
if (!valid) {
vm.$validator.flag(property, {
touched: true,
dirty: true
});
}
});
});
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/
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);
}
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
I have the following Schema:
Games.attachSchema(new SimpleSchema({
title: {
type: String,
label: "Title",
max: 30
},
multiplayer: {
type: Boolean,
label: "Multiplayer",
denyUpdate: true
},
description: {
type: String,
label: "Description",
custom: function() {
var multiplayer = this.field("multiplayer");
if (multiplayer.isSet && multiplayer.value && !this.isSet) return "Description is empty!";
return true;
}
}
}));
My goal is to check if description is empty, but only if the checkbox multiplayer has been checked. If the checkbox has not been checked, the description should not be mandatory to fill in.
I tried the code above, but it does not validate. Even if I do not have an description and I checked the checkbox, I am able to submit the form.
I found the proper documentation and I solved it like this:
{
description: {
type: String,
optional: true,
custom: function () {
var shouldBeRequired = this.field('multiplayer').value;
if (shouldBeRequired) {
// inserts
if (!this.operator) {
if (!this.isSet || this.value === null || this.value === "") return "required";
}
// updates
else if (this.isSet) {
if (this.operator === "$set" && this.value === null || this.value === "") return "required";
if (this.operator === "$unset") return "required";
if (this.operator === "$rename") return "required";
}
}
}
}
}
I think the problem is with your validation logic. Try changing it to :
if (multiplayer.isSet && multiplayer.value && this.isSet && this.value == "")
return "Description is empty!";