var text6 = document.getElementById("text6").value;
var regularExpression1 = /^[1-9]?[0-9]{1}$|^100$/;
if (!text6.match(regularExpression1)){
alert("Please enter Valid Age");
return false;
}
This code is not working properly
Don't use a regexp. Use this function for checking whether something is a number
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
And for your case
function isIntegerBetween0And100(n) {
return isNumber(n) && n>0 && n<=100 && n%1===0;
}
Much faster :)
Your regex is using | but without ().
/(^[1-9]?[0-9]{1}$|^100$)/ would work, but it could be better. This expression can be simplified to /^([1-9]?\d|100)$/, i.e. there's no need to repeat ^ or $, [0-9] can be \d, and {1} is always unnecessary.
I'm not sure regex is best for validating an age, I'm not sure why you can't just simplify it to /^\d{1,3}$/. Things can be older than 100, even people.
I would also validate fields using /regex/.test() instead of string.match(/regex/).
If you have an age range limit, then test that in 'normal code' not regex, it would be easier to follow and modify (if your upper limit changes).
Related
I'm trying to find a JavaScript regular expression to accept numbers less then -50.0 or greater than 80.0.
Expression below does not work:
/^([-][5][0]\.[0]|[-][0-4][0-9]\.[0-9]|[-][0-9]\.[0-9])|([0]\.[0]|[1-9]\.[0-9]|[0-7][0-9]\.[0-9]|[8][0]\.[0])$/
RegEx is used for pattern matching, not for something like this. Just parse the input as a number and compare its value.
function checkValue(input){
var number = parseInt(input);
if (number === NaN) throw new Error('input was not a number') /* error checking */
if (number < -50 || number > 80) return true;
return false;
}
Edit: you should try to do some form of validation upstream if you can. RegEx is not suited for this. Feel free to post more of the context code and we can see how to best validate here.
You can use this regex:
/(?:^|[^.])(-([56]\d|\d{3,})(?:\.\d{1,2})?\b|\b([89]\d|\d{3,})(?:\.\d{1,2})?\b)/gm
RegEx Demo
I've been looking on the internet but couldn't find a proper solution to my problem.
I have two use inputs. One is Age. The other is Name.
Age must be a number. Name must be a word, containing only characters.
if(age==number $$ name == characters){
// do something
}else{
// do something else
}
I tried:
if(Math.floor(num) == num $$ Math.floor(name) != name){
// do something
}else{
// do something else
}
But no luck whastsoever.
If you know how to do this could you let me know. Thanks a lot.
The regex solution is probably the simplest given that your input will be strings anyway.
Try this:
if (/^\d+$/.test(age) && /^\D+$/.test(name)) {...}
The main difference with the ones posted above is in the ^ and $; these will make sure that the string containts only the specified character, as opposed to them containing at least one.
You could do this
if (+age==age && name!=+name) {
It checks that both conditions are verified :
age strictly contains a number
name isn't a number
But it's hard to define a strict rule for a name. Here's a name in my country : "Dupé d'Egïe"
Supposing you'd want to accept for the name only "Letters from a-z and spaces" (which is probably a bad idea), then you may do
if (+age==age && /^[a-z ]+$/.test(name)) {
To test if age contains only digits and name contains no digit, you may do
if (/^\d+$/.test(age) && /^\D+$/.test(name)) {
You could use the javascript function parseInt(value), if the result is NaN, It's not a number
if(parseInt("54")) {
console.log("It's a number");
} else {
console.log("It's not");
}
I am having a hard time figuring out how RegExp work.
I need to rewrite some ASP code into html and js, and I've hit an obstacle in this part:
<asp:RegularExpressionValidator runat="server" id="RegExpValidator" controltovalidate="FileName" Display="Dynamic" ValidationExpression="[^#%&*:<>?/{|}]+">
Now, what I do is create an input textbox which will run a js function whenever its content is changing.
<input type="text" id="fileNameTextBox" class="ms-input" size="35" maxlength="123" onchange="regexValidator(this);"/>
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else {
// Regex stuff goes in here
}
}
Now, for the life of me I can't figure out how to construct the regular expression. The ValidationExpression field i assume checks for invalid characters though it doesn't seem to be a properly constructed regex, and I can't figure out how to write it into a proper one to use with js. Could someone help me out with this?
If you want the regex to check for invalid characters in the field, you can use this.
^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.
You are almost there. Now you just need to make sure, that your string only consists of valid characters. Do this by adding anchors for the beginning and end of string, thus ensuring that the repeated sequence covers the whole string:
ValidationExpression="^[^#%&*:<>?/{|}]+$"
EDIT: I just realised that you probably also want to know how to create a regular expression from a string. You can simply pass a string to a regex constructor:
new RegExp(validationExpressionGoesHere);
[^#%&*:<>?/{|}]+ looks like a valid expression to me (although typically regular expressions are enclosed in forward-slashes). It's basically checking to see of the filename contains any of the illegal characters within the square brackets (apart from the caret ^ which indicates negation).
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else if(val.match(/[^#%&*:<>?/{|}]+/)) {
// Valid
}
else {
// Invalid
}
}
I am trying to learn JavaScript... I have function like, I take the format user id field... which is an email address and try to check if it matches below condition. However even thought I give the user name >3 and domain as gmail.com, I still get false return...Can someone please check and let me know why it is going into the if loop, do I have to trim the text or something.
Also if you can tell me how to write this effectively using jQuery that would help me learn. But if you think I am mixing two thing here... My priority is first question above.
function isValidate(eltt) {
var flag = true;
var upos = eltt.indexOf("#");
var uendpos = eltt.indexOf(".com");
var totlength = eltt.length;
var domain = eltt.slice(upos,totlength);
if ( upos < 3 | domain!="gmail.com" | uendpos=== -1) {
flag=false;
}
return flag;
}
First, the problem is that you're using | instead of ||. (The | is a bitwise or, which in this case will yield a basically random result by combining the bits of the binary representation of your conditions. Chances are, you'll never need |; so use || and forget that | even does anything by itself.)
Second, this validation would be easier with a regular expression:
if (!eltt.match(/^.{3,}#gmail\.com$/)) {
return false;
}
That is, it must start with (^) at least three characters .{3,}, followed by the literal text #gmail.com, with nothing after it ($).
I am trying to get a value from input field.
I want to check if the string has % or * at the beginning of the string then show an alert.
if (/^[%*]/.test(document.getElementById("yourelementid").value))
alert("Where can I find a JavaScript tutorial?");
By way of explanation: the regular expression /^[%*]/ means:
^ match the beginning of the string, followed immediately by
[%*] any one of the characters inside the brackets
Testing the entered value against that regex will return true or false.
getElementById(ID).value.charAt(0);
I'm sure you can figure out the rest. Please do some research first as things like this should be really easy to find by googling it.
You can use the substring method, for example:
data.substring(0, 1) === '%'
if(data.substring(0, 1) === '%' || data.substring(0, 1) === '*')
{
alert("Not allowed");
}
or you can try the regex way.
You can do that by using the indexOf method of strings.
var s = "%kdjfkjdf";
if (s.indexOf("%") == 0 || s.indexOf("*") == 0)
{
// do something
}
You can also use regular expressions too as pointed out in #nnnnnn's answer.
Refer to below link.
javascript pattern matching
var str="%*hkfhkasdfjlkjasdfjkdas";
if(str.indexOf("%") === 0|| str.indexOf("*") === 0){
alert("true");
}
else{
alert("false");
}
please check fiddle here.
http://jsfiddle.net/RPxMS/
you can also use prototype plugin for javascript which contains method startWith.
if(str.startWith("%"))
{
// do
}
check the details in the link: click here