$("#pincode").blur(function () {
var pincode = $("#pincode").val().trim();
var pattern = /^[0-9]{6}$/;
if (pincode != "" && !IsPatternFormate(pincode, pattern)) {
$("#pincode").addClass('invalidValidation');
document.getElementById('pincode')
.setCustomValidity('please enter data in proper formate');
}
});
var IsPatternFormate = function (value, pattern) {
var match = pattern.test($(value));
console.log(match);
}
i don't know why, match always return me false value.
var IsPatternFormate = function (value, pattern) {
if(pattern.test(value)){
return true;
}else{
false;
}
}
Change your IsPatternFormate function
Related
I am currently implementing a javascript function to judge if user id and name matches or not.
function name_match(user_id, user_realname) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
namesref.on("value", function(snapshot) {
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
return true;
}
});
});
return false;
}
However, regardless of input, it will initially return false. I think this is because it will go to "return false" while firebase data is loading.
So, even if eventually returns true, since the first-time return value is false, it causes a problem in like this (in another function).
function name_match2() {
var user_id = document.getElementById("user-id").value;
var user_realname = document.getElementById("user-realname").value;
if(!name_match(user_id, user_realname)) return -1;
return 0;
}
And it will return -1.
Can you explain how to solve this problem?
As explained by Daniel in the comment, outer function never returns true. The async solutions could be these :)
function name_match(user_id, user_realname) {
return new Promise(function (resolve, reject) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
namesref.on("value", function(snapshot) {
var matched = false;
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
matched = true;
}
});
if (matched) {
resolve()
} else {
reject()
}
});
});
}
On the other side of calling function
name_match('userId', 'userName').then(function(){
//matched
}, function(){
//unmatched
});
Other way would be to use Callbacks:
function name_match(user_id, user_realname, cb) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
namesref.on("value", function(snapshot) {
var matched = false;
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
matched = true;
}
});
cb(matched);
});
}
In this case:
name_match('userId', 'userName', function(matched) {
console.log(matched);
})
Here is a small adaptation of Suryapratap solution, using the once() method, which
"Listens for exactly one event of the specified event type, and then stops listening.", and
Returns a Promise
... instead of using the on() method which sets a listener.
function name_match(user_id, user_realname) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
return namesref.once('value').then(function(snapshot) {
var matched = false;
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
matched = true;
}
});
return matched;
});
}
I have been trying to translate my code from es6 to es5 because of some framework restrictions at my work... Although I have been quite struggling to locate what the problem is. For some reason the code does not work quite the same, and there is no errors either ...
Can someone tell me If I have translated properly ?
This is the ES6 code :
function filterFunction(items, filters, stringFields = ['Title', 'Description'], angular = false) {
// Filter by the keys of the filters parameter
const filterKeys = Object.keys(filters);
// Set up a mutable filtered object with items
let filtered;
// Angular doesn't like deep clones... *sigh*
if (angular) {
filtered = items;
} else {
filtered = _.cloneDeep(items);
}
// For each key in the supplied filters
for (let key of filterKeys) {
if (key !== 'TextInput') {
filtered = filtered.filter(item => {
// Make sure we have something to filter by...
if (filters[key].length !== 0) {
return _.intersection(filters[key], item[key]).length >= 1;
}
return true;
});
}
// If we're at TextInput, handle things differently
else if (key === 'TextInput') {
filtered = filtered.filter(item => {
let searchString = "";
// For each field specified in the strings array, build a string to search through
for (let field of stringFields) {
// Handle arrays differently
if (!Array.isArray(item[field])) {
searchString += `${item[field]} `.toLowerCase();
} else {
searchString += item[field].join(' ').toLowerCase();
}
}
// Return the item if the string matches our input
return searchString.indexOf(filters[key].toLowerCase()) !== -1;
});
}
}
return filtered;
}
And this is the code I translated that partially 99% work ..
function filterFunction(items, filters, stringFields, angular) {
// Filter by the keys of the filters parameter
var filterKeys = Object.keys(filters);
// Set up a mutable filtered object with items
var filtered;
// Angular doesn't like deep clones... *sigh*
if (angular) {
filtered = items;
} else {
filtered = _.cloneDeep(items);
}
// For each key in the supplied filters
for (var key = 0 ; key < filterKeys.length ; key ++) {
if (filterKeys[key] !== 'TextInput') {
filtered = filtered.filter( function(item) {
// Make sure we have something to filter by...
if (filters[filterKeys[key]].length !== 0) {
return _.intersection(filters[filterKeys[key]], item[filterKeys[key]]).length >= 1;
}
return true;
});
}
// If we're at TextInput, handle things differently
else if (filterKeys[key] === 'TextInput') {
filtered = filtered.filter(function(item) {
var searchString = "";
// For each field specified in the strings array, build a string to search through
for (var field = 0; field < stringFields.length; field ++) {
// Handle arrays differently
console.log(field);
if (!Array.isArray(item[stringFields[field]])) {
searchString += item[stringFields[field]] + ' '.toLowerCase();
} else {
searchString += item[stringFields[field]].join(' ').toLowerCase();
}
}
// Return the item if the string matches our input
return searchString.indexOf(filters[filterKeys[key]].toLowerCase()) !== -1;
});
}
}
return filtered;
}
These two lines
searchString += `${item[field]} `.toLowerCase();
searchString += item[stringFields[field]] + ' '.toLowerCase();
are not equivalent indeed. To apply the toLowerCase method on all parts of the string, you'll need to wrap the ES5 concatenation in parenthesis:
searchString += (item[stringFields[field]] + ' ').toLowerCase();
or, as blanks cannot be lowercased anyway, just use
searchString += item[stringFields[field]].toLowerCase() + ' ';
Here is a translated code from babeljs itself, as commented above.
'use strict';
function filterFunction(items, filters) {
var stringFields = arguments.length <= 2 || arguments[2] === undefined ? ['Title', 'Description'] : arguments[2];
var angular = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
// Filter by the keys of the filters parameter
var filterKeys = Object.keys(filters);
// Set up a mutable filtered object with items
var filtered = void 0;
// Angular doesn't like deep clones... *sigh*
if (angular) {
filtered = items;
} else {
filtered = _.cloneDeep(items);
}
// For each key in the supplied filters
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
var _loop = function _loop() {
var key = _step.value;
if (key !== 'TextInput') {
filtered = filtered.filter(function (item) {
// Make sure we have something to filter by...
if (filters[key].length !== 0) {
return _.intersection(filters[key], item[key]).length >= 1;
}
return true;
});
}
// If we're at TextInput, handle things differently
else if (key === 'TextInput') {
filtered = filtered.filter(function (item) {
var searchString = "";
// For each field specified in the strings array, build a string to search through
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = stringFields[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var field = _step2.value;
// Handle arrays differently
if (!Array.isArray(item[field])) {
searchString += (item[field] + ' ').toLowerCase();
} else {
searchString += item[field].join(' ').toLowerCase();
}
}
// Return the item if the string matches our input
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return searchString.indexOf(filters[key].toLowerCase()) !== -1;
});
}
};
for (var _iterator = filterKeys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
_loop();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return filtered;
}
p.s. Or there is a better way to use babeljs directly without manually converting it.
Below is a bit of script I'm using in related to a form for a site. I'm trying to get it to redirect to a specific page if the first two functions aren't valid.
What's happening is that the redirect is happening even if the functions are valid
I'm sure I'm missing something really simple here...
Any help appreciated!
(function(){
var f1 = fieldname2,
valid_pickup_postcode = function (postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
var f2 = fieldname7,
valid_dropoff_postcode = function (postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
if( AND(f1,f2))
{
if( valid_pickup_postcode(f1) && valid_dropoff_postcode(f2))
{
return 'Please select the vehicle you require for your delivery';
}
else
{
return window.location.href = "http://www.bing.com";
}
}
else
{
return '';
}
})()
(function() {
var f1 = fieldname2,
valid_pickup_postcode = function(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
var f2 = fieldname7,
valid_dropoff_postcode = function(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
if (AND(f1, f2)) {
if (valid_pickup_postcode(f1) && valid_dropoff_postcode(f2)) {
return 'Please select the vehicle you require for your delivery';
} else {
// return window.location.href = "http://www.bing.com";
window.location.replace("http://www.bing.com");
}
} else {
return '';
}
})()
window.location.replace("http://www.bing.com"); should do the trick
Update: I have made small changes to make your code work. For something that's as straightforward as validating pickup and dropoff postal codes, the JS isn't (or shouldn't be) very complicated :) Here's a simpler version that will work
function myValidator(f1, f2) {
// Validate pickup postal code
function pickup_postcode(postcode) {
if (postcode) {
if (isNaN(postcode)) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
} else {
return false;
}
} else {
return false;
}
}
// Validate dropoff postal code
function dropoff_postcode(postcode) {
if (postcode) {
if (isNaN(postcode)) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
} else {
return false;
}
} else {
return false;
}
}
if (pickup_postcode(f1) === true && dropoff_postcode(f2) === true) { // If both pickup and dropoff postal codes are ok return a message prompting vehicle selection
return 'Please select the vehicle you require for your delivery';
} else { // Invalid pickup or dropoff postal code
// Redirect to website because either pickup or dropoff postal code is invalid
window.location.replace("https://www.bing.com");
}
}
myValidator("X909EF", "X909EE"); // Call it this way
I have these two functions:
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
return false;
} else {
return true;
}
}
}
The problem is that when I test the email like this if(!self.validateEmails(multipleEmails)) { i get true or false based only on the first email in the string, but I want to test for any email in the string.
Thank you!
The problem is your if/else block; You are returning under both conditions. Which means that it leaves the function after evaluating only one element.
I've modified validateEmails to demonstrate what you probably want to do:
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
return false;
}
}
return true;
}
how about this?
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
var errors = [];
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
errors[i] = result[i] + ' is not valid.';
}
}
if (errors.length > 0) {
alert(errors.join('\n'));
return false;
} else {
return true;
}
}
in case you use jquery-validate the validation method would look like:
jQuery.validator.addMethod("separated_emails", function(value, element) {
if (this.optional(element)) {
return true;
}
var mails = value.split(/,|;/);
for(var i = 0; i < mails.length; i++) {
// taken from the jquery validation internals
if (!/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(mails[i])) {
return false;
}
}
return true;
}, "Please specify a email address or a comma separated list of addresses");
I find the most maintainable way is to use a variable to store the return output.
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
var allOk = true;
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
allOk = false;
}
}
return allOk;
}
This code below is perfect to validate multiple email addresses separated with comma or semicolon using JQuery:
var emailReg = new RegExp(/^([A-Z0-9.%+-]+##[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+##[A-Z0-9.-]+.[A-Z]{2,6}))*$/i);
var emailText = $('#email').val();
if (!emailReg.test(emailText)) {
alert('Wrong Email Address\Addresses format! Please reEnter correct format');
return false;
}
I am building a querystring and want to exclude keys if vals are empty, what's a proper way?
setQueryString: function () {
var keyword = $('#keyword').val();
//how to exclude it if keyword is empty?
var params = {
"keyword": $.trim(keyword)
};
return params;
}
take into account, that I will have 20+ inputs like keyword..trying to avoid lots of IF statements
If you have multiple params and you don't want lots of if statements:
setQueryString: function () {
var params = {
'param1': $.trim($('#param1').val()),
'param2': $.trim($('#param2').val())
}
for (p in params) {
if (params.p == null || params.p == '') {
delete params.p;
}
}
return params;
}
Don't set it if it's empty is all:
var keyword = $.trim($('#keyword').val());
var params = {};
if(keyword) {
params.keyword = keyword;
}
return params;
(edit)
If you have lots of things to check, consider using either a loop:
var items = {
keyword: $.trim($('#keyword').val())
// etc.
};
var params = {};
for(var x in items) {
if(items.hasOwnProperty(x) && items[x]) {
params[x] = items[x];
}
}
return params;
or a function of some kind, for example:
var params = {};
function check(name) {
var value = $.trim($('#' + name).val());
if(value) {
params[name] = value;
}
}
check('keyword');
// etc.
return params;
As an empty string is a falsy value in JavaScript you can simpley check if val() is true:
setQueryString: function () {
var keyword = $('#keyword').val();
if(keyword){
var params = {
"keyword": $.trim(keyword)
};
return params;
}
}
Try something like:
setQueryString: function () {
var keyword = $.trim($('#keyword').val());
var params = {};
if(keyword !== undefined && keyword !== '') {
params.keyword = keyword;
}
return params;
}
I believe you need extend: http://api.jquery.com/jQuery.extend/