Javascript Form validation with substr - javascript

This is part of a javascript to validate a form. This checks to see if it is empty.
if (form.redoarr.value == "") {
alert("Has to be higher");
form.redoarr.focus();
return false;
}
I want to make sure that the 4 digit number entered begins with a 2 digit number under 75. It also has to end in a 2 digit number under 40. How can I use substr to extract the first two digits and make sure they are under 75 and the last two digits and make sure they are under 40. I don't need anything complicated as it's for a single in house user on a private form. I can't just use < 7641 as 1849 is not okay (for instance).

Notwithstanding the usual caveats about never validating a form only in JavaScript (rather than using a server-side language), REGEX is a good fit for this:
let
err,
val = form.redoarr.value
;
if (!val)
err = 'No value entered';
else if (!/^([0-6][0-9]|7[0-4])([0-3][0-9])$/.test(val))
err = 'Value must be four digits, with the first two under 75 and the last two under 40';
if (err) {
form.redoarr.focus();
alert(err);
return false;
}
REGEX is cleaner as you don't need to create any variables. However here's how you'd do it via substring:
let
nums_1 = val.substr(0, 2),
nums_2 = val.substr(2)
;

I hope this solution helps
var value = form.redoarr.value;
var re = /^\d{4}$/;
var error = '';
var first_two_digits = '';
var last_two_digits = '';
if ( !re.test(value) ) {
error = 'Value must be four numbers';
}
first_two_digits = value.substr(0, 2);
last_two_digits = value.substr(2);
if (Number(first_two_digits) >= 75 || Number(last_two_digits) >= 40) {
error = 'Invalid number provided';
}
if (error) {
alert(error);
return false;
}

Related

check if an input is of this form

I have a code where the user enters multiple strings and I store them in an array, then I want to check if all the inputs are valid.
An input valid is a number with the same character repeated 3 times.
For example : '333', '999', '222', ...
What I have tried :
let valid = true;
inputs.forEach((input) => {
if (input.length !== 3 || isNaN(input)) {
valid = false;
} else {
const first = input[0];
for (let i = 1; i < 3; i++) {
console.log(first,input[i])
if (input[i] !== first) {
valid = false;
}
}
}
});
console.log(valid);
this code is working and I want to know if can I do better it seems like I used too much code for this simple task and I want to know if there is a simpler code when I searched in the interned they suggest rejex but this is so complicated for me thank you for helping me
First of all for a beginner your solution is good and correct congrats however you can optimize it and make it simpler
you can use every instead of forEach there is no need to check all the inputs once you find an invalid one
instead of loop through the input you can check if it is not divisible by 111 ;)
if(parseInt(input) % 111 !== 0) valid = false;
You could use Array#every.
let valid = inputs.every(s => s.length === 3 && !isNaN(s)
&& [...s].every(c => c === s[0]));
This could be shortened with a regular expression:
let valid = inputs.every(s => /^(\d)\1{2}$/.test(s));

How can I create a loop for a prompt, when the answer is unacceptable for a criteria?

so I've been working on a password generator and I have it working aside from 2 things. The password must be within 8-128 characters long. I have a prompt that asks the user how long they would like the password to be and then a few other prompts about including symbols, uppercase, lowercase, and numbers. However, when the user answers with anything bellow 8 or above 128 I would like an alert to say "password must be at least 8 characters long and shorter than 128" then loop back to the prompt asking them again how long they would like the password to be.
I can not for the life of me figure out how to do this. the obvious solution to me was a while loop however I am not experienced in building those.
I also want a minimum of one character type selected before the "confirm" system ends and to loop back to the beginning of the confirms for upper, lower, symbols, and numbers so the user has to pick at least one.
any help would be greatly appreciated.
thank you!
here is the code for the password length
var passLength;
while (passLength >= 129 || passLength <= 7) {
passLength = parseInt(prompt('How many charcters would you like? (8-128)'))
if (passLength <= 128 || passLength >= 8) {
break;
}
alert("Password length must be 8 to 128 characters long!");
}
here is the code for the separate characters that I need at least one of to be selected.
var chosenCharactersArr = []
var passwordstring = ''
if (confirm('would you like Capital letters?')) {
chosenCharactersArr.push(upperCase)
}
if (confirm('would you like to include lowercase letters?')) {
chosenCharactersArr.push(lowerCase)
}
if (confirm('would you like to include numbers?')) {
chosenCharactersArr.push(numbers)
}
if (confirm('would you like to include symbols?')) {
chosenCharactersArr.push(symbols)
}
You have an error with your length check. You cannot use || in this case because you want to check for the lower- and upper limit to be both valid, therefore &&.
For the question cycle, you can use a while (true) loop that you can break once you are done with the questions i.e. config in your case.
I use an object to store the config values with defaults. You could also use an array. However, you have to manage the indices somehow.
const TYPE_NUMBER = 0;
const TYPE_BOOLEAN = 1;
const TYPE_STRING = 2;
const config = {
len: 8,
upc: false,
loc: false,
num: false,
sym: false
};
while (true) {
const len = ask('How many charcters would you like? (8-128)', TYPE_NUMBER);
if (len <= 128 && len >= 8) {
config.len = len; break;
} else {
alert("Password must be 8 to 128 characters long!");
}
}
const upc = ask('Would you like to use capital letters?', TYPE_BOOLEAN);
if (upc) { config.upc = upc; }
// ... repeat the same for the other questions ...
console.log(config);
function ask(msg, type) {
let result;
if (type === TYPE_BOOLEAN) {
result = confirm(msg);
} else if (type === TYPE_NUMBER) {
result = parseInt(prompt(msg));
} else if (type === TYPE_STRING) {
result = prompt(msg);
} else {
result = "";
}
return result;
}

remove decimal in javascript

I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?

textbox must contain number or letter validation on javascript without regex

Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.

JQuery Phone Number Validation

I've am using jQuery validation plugin to validate a mobile phone number and am 2/3 of the way there.
The number must:
Not be blank - Done,
Be exactly 11 digits - Done,
Begin with '07' - HELP!!
The required rule pretty much took care of itself and and I managed to find the field length as a custom method that someone had shared on another site.
Here is the custom field length code. Could anyone please suggest what code to add where to also require it begin with '07'?
$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 11;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "* Your phone number must be 11 digits");
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
$(document).ready(function(){
$("#form").validate();
});
The code in the question seems a very complicated way to work this out. You can check the length, the prefix and that all characters are digits with a single regex:
if (!/^07\d{9}$/.test(num)) {
// "Invalid phone number: must have exactly 11 digits and begin with "07";
}
Explanation of /^07\d{9}$/ - beginning of string followed by "07" followed by exactly 9 digits followed by end of string.
If you wanted to put it in a function:
function isValidPhoneNumber(num) {
return /^07\d{9}$/.test(num);
}
If in future you don't want to test for the prefix you can test just for numeric digits and length with:
/^\d{11}$/
You could use this function:
function checkFirstDigits(s, check){
if(s.substring(0,check.length)==check) return true;
return false;
}
s would be the string, and check would be what you are checking against (i.e. '07').
Thanks for all the answers. I've managed to come up with this using nnnnnn's regular expression. It gives the custom error message when an incorrect value is entered and has reduced 35 lines of code to 6!
$.validator.addMethod("phone", function(phone_number, element) {
return this.optional(element) || /^07\d{9}$/.test(phone_number);
}, "* Must be 11 digits and begin with 07");
$(document).ready(function(){
$("#form").validate();
});
Extra thanks to nnnnnn for the regex! :D
Use indexOf():
if (digits.indexOf('07') != 0){
// the digits string, presumably the number, didn't start with '07'
}
Reference:
indexOf().

Categories