i want to validate a input by regex. if user enter any character with in a to z or A to Z then it will not accepted but if user enter + sign or bracket or any digit then it will be accepted. i use the regex but it did not work as per my requirement.
var regEx = '/^[A-Za-z]*$/';
if (flag) {
var val = jQuery.trim($("input[id*='txtfphone']").val())
if (val.match(regEx)) {
if (_AdjustHeight == 0) {
$(".ui-dialog").animate({ height: '+=' + dialog_loader.height + 'px' }, 600, function () {
_AdjustHeight = 1;
$('#feed_loader').fadeIn('slow').html('<span>' + dialog_Msg.Invalid_Phone + '</span>');
$("input[id*='txtfphone']").focus()
});
}
else if (_AdjustHeight == 1) {
$('#feed_loader').fadeOut('slow', function () {
$('#feed_loader').html('<span>' + dialog_Msg.Invalid_Phone + '</span>');
}).fadeIn('slow');
$("input[id*='txtfphone']").focus()
}
flag = false;
return false;
}
}
so help me with right regex.
it will be accepted if user enter data like
+913325806589
+91 33 25806589
913325806589
91 33 25806589
91 (33) 25806589
+91 (33) 25806589
but if user enter any alphabet as a input then it will not be accepted. like
aaab
+a913325806589
+91332a5806589
+91332a5806589b etc
a to z any character will not be accepted. thanks
does this one meets your need?
var regEx = /^\+?\d+[\d\s]*(\s*\(\d+\)\s*\d*)*$/ //no quote !!
for your
var regEx = '/^[A-Za-z]*$/'
you have defined the regEx to a string, so it won't take any effect.
The regrex you are using is anchored at both the beginning and end, which means it will only match when the input contains only letters. It would not, for example, match "12a".
It also fails to check for all of the other invalid characters you haven't mentioned... !£## etc.
It would be better to use a regex that matches what you do want, and then see if the input fails to match.
From your description and examples, this should match valid input:
/^\s*\+?[\d\s]*(\([\d\s]+\)?)[\d\s]*$/
You then need to negate your match test:
if (!val.match(regEx)) {
Related
I need to validate a input field which should contain at least x number of numeric characters.
eg: let say I need to input value has at least 5 numeric characters
12345 - valid
AB12345 - valid
123456 - valid
AB312312 - valid
asd - not valid
213 - not valid
First I tried with input.length, but I don't know it will have a leading letters or not, so length doesn't help for me
how should I do this validation with jquery or javascript ?
Let say you are looking at validating 5 numeric then you can use regular expression /(?=(?:[\d]){5}).
What this expression does is that;
(?=) means start looking ahead
(?:[\d]) means match digits but don't capture them
{5} means (?:[\d]) (match digit) do 5 times
"use strict";
let numbers = [ '12345', 'ABC12345', '123456', 'AB312312', 'asd', '213'];
numbers.forEach(number=> {
if (/(?=(?:[\d]){5})/.exec(number)) {
console.log(number + " is valid.");
};
});
Using regular expressions will do the trick
function check(str,x){
var pattern = '^[a-zA-Z0-9]*[0-9]{'+x+'}[a-zA-Z0-9]*$';
if(str.match(pattern)) return true;
return false;
}
How about something like this
x = 5;
myString = "AB12345";
if (myString.replace(/[^0-9]/g,"").length >= x) {
alert('valid');
} else {
alert('not valid');
}
see this jsfiddle.
If
inputValue.replace(/[^0-9]/g,"").length < 5
then input field is invalid.
I am trying to restrict the user somewhat regarding the username they can use, based on length and context.
Here, I am trying to make my username label red when a forbidden word is found when the user leaves the current textbox.
Although the code looks just fine to me, it seems like it completely ignores the forbidden words and makes the label green anyway if the other criteria a met. What is wrong with my code?
var username = document.forms.LogInForm.username;
username.onblur = function() {
var forbiddenWords = ["fff, dddd, aaa, rrrr, oooo"];
var regex;
var username_value = this.value.split('');
for (var a = 0; a < forbiddenWords.length; a++) {
regex = new RegExp('\\b' + forbiddenWords[a] + '\\b');
if (username_value[username_value.length - 1] === "-" || username_value[username_value.length - 1] === "_") {
console.log('Username cannot end in dash (-) or underscore (_). We removed it for you!');
this.value = this.value.slice(0, -1);
}
else if (this.value.length < 4) {
console.log('Username cannot be less than 4 characters');
document.getElementById('username_label').style.color = "red";
}
else if (username.value.search(regex) >= 0) {
console.log('Username contains swearing word. Please, remove it');
document.getElementById('username_label').style.color = "red";
}
else {
document.getElementById('username_label').style.color = "green";
}
}
};
var forbiddenWords = ["fff, dddd, aaa, rrrr, oooo"];
is most likely a mistake and should read
var forbiddenWords = ["fff", "dddd", "aaa", "rrrr", "oooo"];
You want an array of separate strings, not a one element array containing string which has some commas and spaces as content.
I probably wouldn't use \b. If you use \b the user could just type a swear word then add any character and the regex will not find anything.
Also, if the last forbidden word is not found validation color shows as passed because of your else statement. You should have a separate loop for forbidden words only, and mark a value as valid or invalid and display colors based on that.
I have an infix expression: ((attribute1*attribute2)/attribute3+attribute4)
It may vary according to the user input. I want to check whether the expression is valid.
Valid example: ((attribute1*attribute2)/attribute3+attribute4)
Invalid example: (attrribute1*attribute2+*(attribute3)
The second one has no closing parenthesis; also the * operator is not needed. How can I perform this sort of validation in javascript?
Now this is my regex:
/ *\+? *\-? *[a-zA-Z0-9]+ *( *[\+\-\*\/\=\<\>\!\&\|\%] *\+? *\-? *[a-zA-Z0-9]+ *)*/
I need a regex for comparison operators like <= , >= , != , == etc. How can I implement this?
You could try something like this:
function validateInfix(infix) {
var balance = 0;
// remove white spaces to simplify regex
infix = infix.replace(/\s/g, '');
// if it has empty parenthesis then is not valid
if (/\(\)/.test(infix)) {
return false;
}
// valid values: integers and identifiers
var value = '(\\d+|[a-zA-Z_]\\w*)';
// the unary '+' and '-'
var unaryOper = '[\\+\\-]?';
// the arithmetic operators
var arithOper = '[\\+\\-\\*\\/]';
// the comparison operators
var compOper = '(\\<\\=?|\\>\\=?|\\=\\=|\\!\\=)';
// if it has more than one comparison operator then is not valid
if (infix.match(new RegExp(compOper, 'g')).length > 1) {
return false;
}
// the combined final regex: /[\+\-]?(\d+|[a-zA-Z_]\w*)(([\+\-\*\/]|(\<\=?|\>\=?|\=\=|\!\=))[\+\-]?(\d+|[a-zA-Z_]\w*))*/
var regex = new RegExp(unaryOper + value + '((' + arithOper + '|' + compOper + ')' + unaryOper + value + ')*');
// validate parenthesis balance
for (var i = 0; i < infix.length; i++) {
if (infix[i] == '(') {
balance++;
}
else if (infix[i] == ')') {
balance--;
}
if (balance < 0) {
return false;
}
}
if (balance > 0) {
return false;
}
// remove all the parenthesis
infix = infix.replace(/[\(\)]/g, '');
return regex.test(infix);
}
The idea is to check first the parenthesis balance, then remove them all given that we only want to validate and not evaluate, and then match the remaining expression to a regex (which may not be perfect, I'm not a regex expert). And... just in case: infix argument must be a string.
Edit
I noticed a couple of details and changed the code a bit:
Added the operators you needed the regex to match too.
Removed white spaces to get rid of regex junk.
Checked if the expression had empty parenthesis.
Checked if the expression had more than one comparison operators.
Changed this \+?\-? by this [\+\-]?.
Changed string match method by regex test method where possible.
Changed this [a-zA-Z0-9] by this (\d+|[a-zA-Z_]\w*) since the first one matches wrong identifiers like 53abc.
For better understanding and clarity, extracted pieces of regex into separate variables and built the final one from these.
Hope this is ok for you now :)
Trying to get the correct regex for this - only letters, spaces, hypens, and commas. So far this only works if you only input 1 charactor. Any more then that, and it returns false. Anyone able to help?
$('#submit').click(function () {
var locationtest = /[^a-zA-Z \-\.\,]/;
if (!locationtest.test($('#location').val())) {
alert('Nope, try again!');
$('#location').val('')
return false;
} else {
alert('You got it!');
}
});`
This should do it, it matches 1 or more characters within the set you described
/^[a-zA-Z \-\,]+$/
I took out the \., your description says letters, spaces, hyphens, commas
You're close, you just need to specify how many times you want the character to appear.
The following code would specify 0 or more times
var locationtest = /[^a-zA-Z -.\,]*/;
And this code would specify 1 or more times
var locationtest = /[^a-zA-Z -.\,]+/;
The importance being the * and + characters.
Add a quantifier + and the global flag /g:
var locationtest = /[^a-zA-Z \-\.\,]+/g;
Your expression is correct, you just need to invert the match result.
/[^a-zA-Z \-\.\,]/
Will match if the string contains any char that is not what you want (the leading ^ in the character class).
I.e remove the !:
var locationtest = /[^a-zA-Z \-\.\,]/;
if (locationtest.test($('#location').val())) {
alert('Nope, try again!');
$('#location').val('')
return false;
} else {
alert('You got it!');
}
Note that empty string will pass as valid, if you don't want that, you can use this instead:
/[^a-zA-Z \-\.\,]|^$/
Here's what I tried...
It works if I only check if the value of the input is lesser than 8, but doesn't work to check if it contains at least 1 letter and 1 digit. What am I doing wrong ? =/
$(document).ready(function() {
var jVal = {
'passWord' : function() {
$('body').append('<div id="nameInfo" class="info"></div>');
var nameInfo = $('#nameInfo');
var ele = $('#password');
var pos = ele.offset();
ra = /^[A-Za-z]+$/;
re = /^[0-9]+$/;
nameInfo.css({
top: pos.top - 3,
left: pos.left + ele.width() + 15
});
if (ele.val().length < 8 & re.test(ele.value) & ra.test(ele.value)) {
jVal.errors = true;
nameInfo.removeClass('correct').addClass('error').html('← too short').show();
ele.removeClass('normal').addClass('wrong');
}
else {
nameInfo.removeClass('error').addClass('correct').html('√').show();
ele.removeClass('wrong').addClass('normal');
}
}
}
$('#password').change(jVal.passWord);
});
ra checks if the password is made ENTIRELY of letters. re checks if the password is made ENTIRELY of numbers. They are mutually exclusive and therefore cannot both be true.
Instead, use ra = /[a-z]/i; re = /[0-9]/;.
EDIT: Also, since you're using jQuery, you should be testing on ele.val(), not ele.value.
You could use a single regex to do everything:
/^(?=.*\d.*)(?=.*[a-z].*)\w{8,}$/i
The first two pieces check for both a digit, and an a-z char in the whole string, and then the last piece ensures it's at least 8 characters. You could change the last \w to . to allow special chars if so desired.