How to check if a input value does / doesnt contain REGEX characters - html

trying to write a password validator using jquery:
my password element is:
<input type="password" id="passwordTxtBox" class="form-control form-control-lg" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" aria-describedby="passwordHelpBlock" name="Password" required>
my jquery code is:
$("#passwordTxtBox").keyup(function () {
var upperCase = new RegExp('[A-Z]');
var lowerCase = new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');
var special = new RegExp('/[^a-zA-Z0-9- ]*$/');
if ($(this).val().length < 9 && $(this).val().length != 0) {
console.log("not long enough");
}
else if (!$(this).val().match(upperCase)) {
console.log("not uppercase");
}
else if (!$(this).val().match(lowerCase)) {
console.log("not lowercase");
}
else if (!$(this).val().match(numbers)) {
console.log("no numbers");
}
else if (!$(this).val().match(special)) {
console.log("no specials");
}
else if ($(this).val().length >= 8 ) {
console.log("length is fine");
}
else if ($(this).val().match(upperCase)) {
console.log("contains uppercase");
}
else if ($(this).val().match(lowerCase)) {
console.log("contains lowercase");
}
else if ($(this).val().match(numbers)) {
console.log("contains numbers");
}
else if ($(this).val().match(special)) {
console.log("contains specials");
}
});
its important that each console log is fired off separately, so i have to read each regex rule separately
however when I fire this off, only the console.logs for the negative cases fire
i.e console.log("not long enough"); console.log("not uppercase");console.log("no numbers");
etc
the instances where the input does contain those characters, the console logs are never fired.
what am i doing wrong?

Related

AngularJS Selects Empty Option Even Valid Option is Avaliable

I'm using AngularJS ver. 1.2.15 on my project. And, I have a select element on one of my views as per below:
<select class="select-white form-control form-select" id="cat2_{{feed.id}}" ng-model="feed.operationstatusid" ng-change="updateCategoryAndStatus(feed, true)"></select>
And, I'm feeding this element like this:
function SetCategory2(cat1Id, feed) {
var feedId = feed.id;
var fromRuleOpStatusId = -1;
$('#cat2_' + feedId).find('option').remove();
if (cat1Id > -1) {
$('#cat2_' + feedId).append($('<option></option>').text(lang.SelectSubCategory).val(0));
$.each($scope.category2, function (index, cat2Item) {
$('#cat2_' + feedId).append($('<option></option>').text(cat2Item.statusdescription).val(cat2Item.id));
});
var isselected = false;
$.each($scope.category2, function (index, cat2Item) {
if (feed.operationstatusid == cat2Item.id) {
$('#cat2_' + feedId).val(cat2Item.id);
fromRuleOpStatusId = -1;
isselected = true;
}
else {
var feedStr = "";
if (feed.title != undefined && feed.title != null) {
feedStr = feed.title.toLowerCase();
}
if ($scope.catTitleRulesTwo) {
$.each($scope.catTitleRulesTwo, function (r_index, r_item) {
if (cat2Item.id == r_item.titleCode && !isselected) {
if (feedStr != undefined && feedStr != null && r_item != undefined && r_item != null) {
String.prototype.contains = function (str) { return this.toLowerCase().indexOf(str) !== -1; };
var text = feedStr;
if (eval(r_item.ruleexpression)) {
$('#cat2_' + feedId).val(cat2Item.id);
fromRuleOpStatusId = cat2Item.id;
isselected = true;
}
}
}
});
}
}
});
if (fromRuleOpStatusId != -1) {
feed.operationstatusid = fromRuleOpStatusId;
}
}
else {
$('#cat2_' + feedId).append($('<option></option>').text(lang.SelectSubCategory).val(0));
}
}
I am aware of the facts about eval function, but the project I'm working on is quite old, so does the code. Anyway, this is about business logic and quite irrelevant with the thing I'm going to ask (or so I was thinking).
As you can see I'm appending all the options before I set the value of the selectbox with using .val(...). I have also checked that values do match along with the data types. But, when I observe this function step by step, I saw that selected value does show up without flaw. After the code finish with my above mentioned function (SetCategory2), code goes through on of the function located on AngularJS file, named xhr.onreadystatechange. It's not a long function, so I'm sharing it also on below.
xhr.onreadystatechange = function() {
if (xhr && xhr.readyState == 4) {
var responseHeaders = null,
response = null;
if(status !== ABORTED) {
responseHeaders = xhr.getAllResponseHeaders();
response = ('response' in xhr) ? xhr.response : xhr.responseText;
}
completeRequest(callback,
status || xhr.status,
response,
responseHeaders);
}
};
After the code released from this function, respective selectbox's value is pointed at the empty option.
I have run into topics which talks about this behaviour might due to invalid option-value match, but as I described above, I append all my options before deciding the value. So, I can't figure out what I'm missing.
Thank you in advance.

using condition in jquery onclick button

Im trying to confirm if the password strength is strong or weak and is the password is strong and when I submit it should have alert message like "You Have Strong Password" and when its weak "Invalid Password"
This is what I am now.
function checkPasswordStrength() {
var passwordStrength = false;
var number = /([0-9])/;
var alphabets = /([a-zA-Z])/;
var special_characters = /([~,!,#,#,$,%,^,&,*,-,_,+,=,?,>,<])/;
if ($('#password').val().length < 8) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('weak-password');
$('#password-strength-status').html("Weak (should be atleast 8 characters.)");
} else {
if ($('#password').val().match(number) && $('#password').val().match(alphabets) && $('#password').val().match(special_characters)) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('strong-password');
$('#password-strength-status').html("Strong");
return passwordStrength = true;
} else {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('medium-password');
$('#password-strength-status').html("Medium (should include alphabets, numbers and special characters.)");
}
}
}
$('#btn-submit').click(function () {
if (passwordStrength == false) {
alert("INVALID PASSWORD");
} else {
alert("You have Strong PASSWORD");
}
</script>
its for Educational Purpose only im just starting jquery..
thank you in advance..
You need to call the function instead of just checking your variable. So rather do
$('#btn-submit').click(function () {
if (checkPasswordStrength() === false) {
instead of
$('#btn-submit').click(function () {
if (passwordStrength == false) {
Then, instead of return passwordStrength = true; you should do just passwordStrength = true and add a return passwordStrength to the very end of your function so it will return either false or true.
It looks like the variable scope is incorrect. var passwordStrength should be put outside of the checkPasswordStrength function.
var passwordStrength
function checkPasswordStrength() {
....

Limit number of characters in input where jquery numpad is used

How would I limit number of characters in input where jquery keypad is used?
HTML
<input id="num-input" type="text" maxlength="3" disabled>
JQUERY
var $numInput;
$(function() {
initKeyboard($('#numeric-keyboard'), $('#num-input'));
$('#num-input').on('keydown', function(e) {
$('#event').text('key: '+e.keyCode);
});
$('#back').on('click', onBackBtn);
$('#forward').on('click', onForwardBtn);
});
function onBackBtn() {
$('input').first().focus();
}
function onForwardBtn() {
$('input').last().focus();
}
function initKeyboard($keyboard, $input) {
$numInput = $input;
$keyboard.on('click', '.key', onKeyPress);
}
function onKeyPress(e) {
var keyValue = $(this).text();
if(keyValue.toLowerCase() === 'delete') {
keyValue = 8;
} else if(keyValue === '') {
return;
} else {
keyValue = keyValue.charCodeAt(0);
}
var e = $.Event("keydown");
e.which = keyValue;
e.keyCode = keyValue;
$numInput.trigger(e);
if(keyValue !== 8) {
$numInput.val( $numInput.val() + $(this).text() );
} else {
$numInput.val( $numInput.val().slice(0, -1) );
}
}
maxlenght is ignorred, I attempted to add if clause to $numInput.val( $numInput.val() + $(this).text() ); this part of the code with var max=3; but again no luck.
I have also tried with out of this code script to limit number of characters for that input but again jquery overtakes it and keep adding characters.
I need t set limit of 3 characters to it.
Any idea?
#num-input is disabled, maybe maxlength need to be set in #numeric-keyboard field?

How to transfer some letters to uppercase dynamically in angular

i got a problem when i was making to capitalize dynamically. In my code i can capitalize any letters but it is not dynamic,the program should guess which letter should it capitalize.For example some text comes from JSON and there should be some comparing that checks texts letters and users inputed letters and then he should guess which letter he must capitalize. if there is some solution for this, please tell me. here is my code :
index.html
<textarea id="fieldId" class="textarea" style="resize: none" cols="30" row="2" ui-mask="{{typetext}}" ng-model="model" data-ng-trim="fasle" ng-trim="false" ng-focus="expression">
</textarea>
scipt.js, thats what i was trying to do.
link: function(scope, iElement, iAttrs, controller) {
controller.$parsers.push(function(inputValue) {
var transformedInput = '';
if (inputValue) {
for (var i = 0; i < inputValue.length; i++) {
if (i === 0 || i === 5) {
transformedInput += inputValue.charAt(i).toUpperCase();
} else {
transformedInput += inputValue.charAt(i).toLowerCase();
}
}
}
if (transformedInput != inputValue) {
controller.$setViewValue(transformedInput);
controller.$render();
}
return transformedInput;
});
})
and controller
app.controller('myController', ['$scope', '$document', function($scope, $document) {
$scope.typetext = "Some Text";
$document.on('keydown', function(e) {
if (e.which === 8 && e.target.nodeName !== "INPUT") {
e.preventDefault();
}
});
}])

Email input form not showing/working properly in different browsers

I have a simple form which only has two input controls: a text box for taking emails, and a submit button.
HTML:
<form class="form-wrapper cf">
<input type="text" placeholder="Enter your email here..." required>
<button type="submit">
Submit
</button>
</form>
JSFiddle: http://jsfiddle.net/ahmadka/aDhUL/
Form has issues in different browsers:
Chrome: Works & displays fine.
iPhone: Works & displays fine.
Firefox 22: placeholder text not shown, and cannot type anything in
the textbox too !
Internet Explorer 10: Works fine, but placeholder text is cropped !
How can I make it cross-browser compatible guys ?
I've tried removing the placeholder and required parameters to make it very simple, but still it doesn't work on Firefox ..
I think you try to run "placeholder" in all browser.
then just attach one .js file that as follow it work Fine in all browser.
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function setPlaceholder() {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
}(this, document, jQuery));
and then just put one script on page.
<script>
$(function() {
$('input, textarea').placeholder();
});
</script>
It Work Fine in All Browser (placeholder)
Actually the problem is with your CSS styling.
You have set the height of the input as 0px. So the input box accepts the input but is not displayed in FF due to the height set to zero.
Your Previous Code is here:
.form-wrapper input {
width: 150px;
height: 0px;
padding: 10px 5px;
New JSFiddle with height set to 10px is here: http://jsfiddle.net/B435n/
And you can use any jQuery plugin for placeholder thing.