JavaScript regular expression 5-5000 - javascript

I know that this:
var regStartMoney = /[1-5][0-9][0-9][0-9]/;
allows you to enter from 1-5999.
how do I do it for a range of 5-5000?

Regex misuse! Just do it the sane way:
var int = parseInt(input,10);
if (isNan(input)) {
alert('Please enter a number.');
} else if (input != int) {
alert('Decimals are not allowed.');
} else if (!(int >= 5 && int <= 5000)) {
alert('Your number must be between 5 and 5000 (inclusive).');
} else {
alert('Your number is valid!');
}

var regStartMoney = /^0*(?:[5-9]|[1-9][0-9][0-9]?|[1-4][0-9][0-9][0-9]|5000)$/;

Why not just:
var money = parseInt(input);
var test = Math.min(Math.max(money, 5), 5000);
if(money !== test) //

You should really convert to a number and compare. But that wasn't your question so here's your answer:
var regStartMoney = /^0*([5-9]|([1-9]\d{0,2})|([1-4]\d{3})|(50{3}))$/;
Here's a test script:
<script>
function checkMoney() {
var money=document.getElementById("money").value;
if (money.match(/^0*([5-9]|([1-9]\d{0,2})|([1-4]\d{3})|(50{3}))$/)) {
alert(money+" is between 5-5000");
} else {
alert(money+" is not between 5-5000");
}
}
</script>
<input id="money"/></br>
<input type="submit" onClick="checkMoney();"/><br/>
Test on jsfiddle

Related

dynamically change error div based on user input

I want to change my error message depending on how many digits the user enters in credit card field. I'm trying to generate the message variable with this:
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
}
creditCardMessage = numberDigit + 'Please enter between 13 and 16';
Then I want to pass the creditCardMessage variable in the following function:
function creditCardNumberEvent () {
if (!isCreditCardValid()) {
showErrorMessage ($cardNumber, creditCardMessage, $cardNumber, 'creditCardError');
} else {
removeErrorMessage($cardNumber, '#creditCardError');
}
}
All I get is the first value - the "too few digits." Thanks in advance.
When running your script, you can call CardNumberValid() which returns a Boolean, meaning you can use it in an if statement, like if(CardNumberValid())
function CardNumberValid() {
var valid = true;
var CardNumber = $("#CardNumber");
if (CardNumber.val().length < 13) {
$("#ErrorMsg").text("Too few digits. Please enter between 13 and 16");
valid = false;
} else if (CardNumber.val().length > 16) {
$("#ErrorMsg").text("Too many digits. Please enter between 13 and 16");
valid = false;
}
if(valid){
$("#ErrorMsg").text("");
}
return valid;
}
$('#Validate').click(function() {
alert("The card number " + (CardNumberValid() ? "is" : "is not") + " valid.");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="CardNumber" />
<div id="ErrorMsg" style="color:red;"></div>
<button id="Validate" type="button">Validate</button>
I think this is what you're trying to achieve:
function logValidationMessage() {
var cardNumber = document.getElementById('cardNumber');
var numberDigits = null;
if (cardNumber.value.length < 13) {
numberDigits = 'Too few digits. ';
} else if (cardNumber.value.length > 16) {
numberDigits = 'Too many digits. ';
} else {
numberDigits = 'Card number is valid.';
}
console.log(numberDigits);
}
document.getElementById('btnCheckCardNumber').addEventListener('click', logValidationMessage);
<input type="text" id="cardNumber" />
<input type="button" id="btnCheckCardNumber" value="Check" />
I did figure this out. I created a function as suggested and passed that function as an argument in another function: (which I now know is a callback function)
function creditCardMessageFunction () {
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
} else {
numberDigit = 'Numeric Values Only. ';
}
creditCardMessage = numberDigit + 'Please enter numbers between 13 and 16.';
return creditCardMessage;
}

Simple validation javascript function

I have this javascript function:
if (myform.telephone.value.length < 10){
jAlert ('Please enter at least 10 characters!',function(){$(myform.telephone).focus();});
return false;
If the user enters less than 10 characters, an alert is triggered. I need to modify the script so that the alert pops if the user enters less than 10 DIGITS (0,1,2,etc)..
How can i do this ?
Update: As the OP correctly pointed out, there was a bug in the previous method. I advise not to use isNan as it is broken. I've updated the answer, code below.
This can be easily done by mathcing the input against a regular expression and then checking if the resulting number has 10 or more digits. Like:
var validate = function(){
var number = tryParseNumber(input.value);
if(number.toString().length < 10){
alert("Invalid input");
} else {
alert("Valid output: " + number);
}
};
var tryParseNumber = function (value) {
if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
return Number(value);
return false;
}
See this Fiddle for a working example.
Try :
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
function phonenumber(inputtxt)
{
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following cod
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

Regular Expressions for phone numbers and mobiles doesn'nt work correctly

I have a function for validating telephone and mobile numbers. Here is part of my function:
function IsPhone(){
var mob = /09[123]\d{8}$/;
var phn = /0\d{10}$/;
for (var i = 0; i < edit_rows.length; i++) {
if (edit_types[i] == 5) {
var phon_val = document.getElementById('phone1').value;
if (phon_val != "") {
if (phon_val.match(mob))
return true;
else if (phon_val.match(phn)) {
if ((phon_val).length == 11)
return true;
}
else {
msg_req += "Invalid format";
return false;
}
}
}
}
return true;
}
But it accepts all of these:
009153842716
09153842716
001234567890
01234567890
what can I do?
I think adding a ^ at the beginning of your expression would fix it. Your current query would match strings like 'thisisaninvalidvalue09153842716'. Adding the ^ makes sure you don't start with invalid input.

NaN message, even when all the Javascript working seems fine in Recursive function

I have written some javascript code in which i have made a recursive function. I am expecting a numeric value however i recieve an NaN. How can i solve this?
<script language="javascript">
function toperform()
{
var proceed=confirm("Do you want to proceed?");
if (proceed==true)
{
var a = checknum("num1");
var b = checknum("num2");
alert("The sum is "+(a+b));
}
else
{
alert("You chose not to proceed!");
}
}
function checknum(arg)
{
var num=parseInt(prompt("Enter "+arg));
if (isNaN(num))
{
alert("Please enter a valid number");
num=checknum(arg);
}
return num;
}
</script>
I think this is more semantic, repeat until get a valid number, but not recursively
function checknum(arg)
{
var num = null ;
while (isNaN(num))
{
if (num != null)
alert("Please enter a valid number");
var input = prompt("Enter "+arg);
num = parseInt(input);
}
return num;
}

JavaScript Form onkeyup Validation Errors

Not getting any errors in Aptana, so something I'm doing probably doesn't make sense. Basically, I am getting the value from a form and checking it against a regex. If the new checked variable isn't empty then I output to a different div that it is valid, and that it is not valid if the variable is empty.
<script type="text/javascript">
var age_regex=/(1[8-9]|2[0-9]|3[0-5])/;
var error_box= document.getElementById('error_box');
function checkAge(x){
var age = document.getElementById(x).value;
var checked_age = test.age_regex(age);
if (checked_age.value != "")
error_box.innerHTML = "Correct!";
else {
error_box.innerHTML = "Incorrect!";
}
}
</script>
Why regex for age ? How about this :
function checkAge(str) {
if(parseInt(str, 10) != str) {
return false;
}
if(parseInt(str, 10) < 18 || parseInt(str, 10) > 35)
{
return false;
}
}

Categories