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.
Related
In my application someone can submit text from another language. I'd like for only English alphanumeric strings to be entered. I've got this JavaScript function working but wondering if this is the best method for doing this?
var string = $('input[name=title]').val();
if((/\d/.test(string) || /[a-zA-Z]/.test(string)) === false) {
alert('Field has no Alphanumeric characters.');
fPass = false;
}
Even if some just enters 1 character I want that to be allowed, as long as it is a number or a character from one of the 26 letters in the English alphabet (case insensitive)
Without using a function here is what I've come up with
if((/[\da-z]/i.test(string)) === false) {
alert('Please use alphanumeric characters.')
}
You can combine your regex into one expression.
function hasAlphanumeric(str) {
return /\d|[A-z]/.test(str)
}
You can use
^[\da-z]+$
let allowAlphanumeric = (str) =>{
return /^[\da-z]+$/i.test(str)
}
console.log(allowAlphanumeric('$##'))
console.log(allowAlphanumeric(''))
console.log(allowAlphanumeric(' '))
console.log(allowAlphanumeric('abchbchdb12e44'))
I have jQuery Validation plugin on a page. When someone types the phone number into the form field, I want the validator to only recognize a certain format (ru):
+#(###)-###-##-##
or
+#-###-###-####
or
+#-###-###-##-##
or
+###########
I have this in .js file:
$.validator.addMethod('customphone', function (value, element) {
return this.optional(element) || /^\+d{1}(\d{3})\d{7}$/.test(value);
}, "Please enter a valid phone number");
$(document).ready(function() {
$('form').validate({
rules: {
phone: 'customphone'
} ...
This is not working for me, does anyone see why? Or is there a better way to do this? :)
You need the following regex:
/^\+(?:\d(?:\(\d{3}\)|-\d{3})-\d{3}-(?:\d{2}-\d{2}|\d{4})|\d{11})$/
See the regex demo
The regex you have ^\+d{1}(\d{3})\d{7}$ has d instead of \d (thus failing to match digits) and unescaped parentheses (thus the pattern did not match literal parentheses).
Breakdown:
^ - start of string
\+ - a literal + symbol
(?:\d(?:\(\d{3}\)|-\d{3})-\d{3}-(?:\d{2}-\d{2}|\d{4})|\d{11}) - two alternatives:
\d(?:\(\d{3}\)|-\d{3})-\d{3}-(?:\d{2}-\d{2}|\d{4}):
\d - a digit
(?:\(\d{3}\)|-\d{3}) - either (123) like substring or -123 substring
-\d{3} - a hyphen followed with 3 digits
- - a hyphen
(?:\d{2}-\d{2}|\d{4}) - 2 digits followed with a hyphen and 2 digits or 4 digits
| - or
\d{11} - 11 digits
$ - end of string
This is not working for me, does anyone see why? Or is there a better
way to do this? :)
There are a couple of issues with your code
As Tushar has pointed out, d will match only d, to match a digit you need \d
Your regex is not affording for many things including (###) and -
I guess you are looking for this regex
/^\+\d(\(\d{3}\)){0,1}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}$/g
It will match for
/^\+\d(\(\d{3}\)){0,1}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}$/g.test("+4(222)-33-33-33"); //true
/^\+\d(\(\d{3}\)){0,1}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}$/g.test("+4(222)-333-333-333"); //true
/^\+\d(\(\d{3}\)){0,1}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}$/g.test("+4(222)333333333"); //true
/^\+\d(\(\d{3}\)){0,1}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}(\-){0,1}\d{2,3}$/g.test("+4333333333"); //true
I am not sure about your javaScript but here is the different regex you have to check for.... I hope this helps.
+#(###)-###-##-##
^\+\d{1}\(\d{3}\)\-\d{3}\-\d{2}\-\d{2}$
+#-###-###-####
^\+\d{1}\-\d{3}\-\d{3}\-\d{4}$
+#-###-##-##
^\+\d{1}\-\d{3}\-\d{2}\-\d{2}$
+###########
^\+\d{11}$
So I would setup a phone is valid flag and test each regex value to determine if one of them is true set this flag to true and it would validate your phone number.
var phoneValid = false;
if(test1 == true || test2 == true || test3 == true || test4 == true) {
phoneValid = true;
} else {
phoneValid = false;
}
I have input as 23 digit key from input box which will be separated by '-'.
E.g: XXXXX-XXXXX-XXXXX-XXXXX
This is expected format means, 5 digit followed by -(hyphen).
Problem:
User can input any data/wrong format, like XXX-XXXXX-XXXXX-XXXXXXX, in this case index of hyphen is invalid. How can I valided the index of hyphen?
I tried:
if((prd_len==23) && (n!=-1))
{
var indices = [];
for(var i=0; i<prd_id.length;i++)
{
if (prd_id[i] === "-")
{
indices.push(i);
}
}
for(var x=0;x<indices.length;x++)
{
if((indices[x]!=5) || (indices[x]!=11) || (indices[x]!=17))
{
$('#msgErr1').text('Please enter valid key.');
flag=1;
}
}
}
where prd_len=length of the accepted input from user.
Try regular expressions
if(input.match(/^(\d{5}-){3}\d{5}$/))
everything is OK
This expression basically reads "five digits and a dash - three times, then five digits". For further reference see
http://www.regular-expressions.info/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
As thg435 said, but more human-readable :-)
var correct = input.match(/^\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d$)
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)) {
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript percentage validation
I want to allow 0.00 to 100.00 only.
function ValidateText(i)
{
if(i.value.length>0)
{
i.value = i.value.replace(/[^\d.d]+/g, '');
}
}
<asp:textbox id="txtrate" runat="server" Width="200px" onkeyup= "javascript:ValidateText(this)"></asp:textbox>
It allows 0-9.0-9. Help me please. Thanks
Now this is some popular question!
This should do:
function validate(s) {
return s.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
}
var test = [
'3.0',
'5',
'99.99',
'100',
'100.00',
'100.01',
'101',
'0.3',
'.5',
'0.567',
];
for (i=0; i<test.length; ++i) {
WScript.StdOut.WriteLine(test[i] + ' => ' + validate(test[i]));
}
Outputs:
3.0 => true
5 => true
99.99 => true
100 => true
100.00 => true
100.01 => false
101 => false
0.3 => true
.5 => false
0.567 => false
Edit: the regexp can be shortened a bit without changing its meaning, credits to 6502
/^(100(\.00?)?|[1-9]?\d(\.\d\d?)?)$/
This expression should allow only what you are asking for
/^[1-9]?\d(\.\d\d?)?|100(\.00?)?)$/
Meaning is
^ start of string
( start of sub-expression ("or" between two possibilities)
[1-9]? an optional non-zero digit
\d followed by a digit
(\.\d\d?)? optionally followed with a dot and one or two digits
| or
100 the string "100"
(\.00?)? optionally followed by a dot and one or two zeros
) end of sub-expression
$ end of string
Try this one
^(?:\d{1,2}(?:\.\d{1,2})?|100(?:\.0?0)?)$
See it here on Regexr
(?:) are non capturing groups, that means the match from this group is not stored in to a variable.
\d{1,2} matches 1 or 2 digits
(?:\.\d{1,2})? This is optional, a . followed by 1 or two digits
or
100(?:\.0?0)?) matches 100 optionally followed by 1 or 2 0
^ matches the start of the string
$ matches the end of the string
Those two anchors are needed, otherwise it will also match if there is stuff before or after a valid number.
Update:
I don't know, but if you want to disallow leading zeros and numbers without two digits in the fraction part, then try this:
^(?!0\d)(?:\d{1,2}(?:\.\d{2})|100\.00)$
I removed the optional parts, so it needs to have a dot and two digits after it.
(?!0\d) is a negative lookahead that ensures that the number does not start with a 0 and directly a digit following.
How about:
var x = '76', // (i.value)
testx = Number(x.match(/\d+/)[0]);
console.log(testx>=0 && testx<=100);
Applied in your function:
function ValidateText(i) {
var val = i.value;
if (val.length>0) {
var test = Number(val.match(/\d+/)[0]);
return test >=0 && test <= 100;
}
return false;
}
Use this regex: ^(?:100(?:\.0{1,2})?|[0-9]{1,2}(?:\.[0-9]{1,2})?)$
Use this:
function ValidateText(i)
{
if(i.value.length>0)
{
i.value = i.value.match(/[1?\d{1,2}\.\d\d]/)[0];
}
}
instead of replacing all that is not (0.00 - 100.00) (as it seems to me you are trying to do), I match the allowed strings and replace the original variable content with only the matched string.
Keep in mind that this will work if you only have 1 match. If you have more, you have to trick a bit the expression and decide how to concatenate the array of results.
I don't actually see this as primarily a regex problem. I'd probably write this, particularly if you want informative error messages out it:
HTML:
<input id="percentValue" type="text" size="20">
<input type="button" value="Check" onclick="checkPercent()">
Javascript:
function checkPercent() {
var o = document.getElementById("percentValue");
var val = o.value;
if (val.length == 0) {
alert("Empty value");
return;
}
var index = val.search(/[^0-9\.]/);
if (index != -1) {
o.selectionStart = o.selectionEnd = index;
alert("Invalid characters");
return;
}
if (val.match(/\./g).length > 1)
{
alert("Number must be of the form n.n");
return;
}
var floatVal = parseFloat(val);
if (floatVal < 0 || floatVal > 100)
{
alert("Value must be between 0.00 and 100.00");
return;
}
alert("Valid value of: " + floatVal.toFixed(2));
}
jsfiddle here: http://jsfiddle.net/jfriend00/rDbAp/