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.
Related
"Write a JavaScript function to find longest substring in a given a string without repeating characters."
Here's what I tried, but it doesn't print anything
function sort(names) {
let string = "";
let namestring = names.split("");
for(let i = 0; i < namestring.length; i++) {
for(let j = 0; j < string.length; j++) {
if(string[j] != namestring[i]) {
string = string + namestring[i];
}
}
}
return string;
}
console.log(sort("google.com"));
What's wrong?
function sort(names)
{
string="";
ss="";
namestring=names.split("");
for(j=0;j<namestring.length;j++) {
for(i=j;i<namestring.length;i++) {
if(string.includes(namestring[i]))
break;
else
string+=namestring[i];
}
if(ss.length<string.length)
ss=string;
string="";
}
return ss;
}
console.log(sort("google.com"));
It's o(n^2) complexity but try this(may be o(n^3) if contains function take o(n) complexity)
function sort(names)
{
string="";
ss="";
namestring=names.split("");
for(j=0;j<namestring.length;j++) {
for(i=j;i<namestring.length;i++) {
if(string.includes(namestring[i])) // if contains not work then
break; //use includes like in snippet
else
string+=namestring[i];
}
if(ss.length<string.length)
ss=string;
string="";
}
return ss;
}
console.log(sort("google.com"));
What are you expecting the answer to be here? Should it be "ogle.com" or "gle.com"? If the first, the below should get you there, if the latter, update the tested = name.charAt(i) in the else to tested = "".
So a few things to note, though you're more than welcome to do as you wish:
1) the function name. This isn't doing a "sort" as far as I can tell, so if this is for your use (or any reuse. Basically, anything more than a one off homework assignment), you may want to rename it to something you'd actually remember (even the example I give is probably not completely best as "pick longest substring" is non-descriptive criteria).
2) variable naming. string and namestring may mean something to you here, but considering we're trying to find the longest substring (with the no double characters) in a string, I felt it was better to have the one we're checking against (tested) and the one we're storing to return later (longest). It helps make sense as you're reading through the code as you know when you are done with a checked string (tested), you want to compare if it is greater than the current longest substring (longest) and if it is bigger, you want it to be the new longest. This will save you a ton of headache to name variables to things that'll help when designing your function as you can get it as close to requirements written down as possible without trying to do some form of substitution or worse, forgetting which variable holds what.
I don't know what you want the result to be in the event that tested length is the same as longest length. Currently I have it set to retain, if you want the most recent, update the check to >=.
Beyond that, I just iterate over the string, setting to the currently tested string. Once double characters are met, I then see if what I just generated (tested) is larger than the current longest and if it is, it is now the longest. Once I finish looping across the string, I have to do the current vs longest check/set again as otherwise, it'd make the final tested meaningless (it went outside the loop before another double character situation was hit).
function pickLongestSubstring(name) {
let tested = "";
let longest = "";
for (let i = 0; i < name.length; i++) {
if (tested.length == 0 || tested.charAt(tested.length - 1) != name.charAt(i)) {
tested += name.charAt(i);
}
else {
if (tested.length > longest.length) {
longest = tested;
tested = "";
}
}
}
if (tested.length > longest.length) {
longest = tested;
}
return longest;
}
console.log(pickLongestSubstring("google.com"))
console.log(pickLongestSubstring("example.com"))
This is a recursive loop that should get the longest string. Uses sort to determine longest string. Works, even if multiple instances of same repeat char.
function longestWithoutRepeat(testString, returnString){
var returnString = returnString || "";
for(var i = 0; i < testString.length; i++) {
if(i > 0){
if(testString[i] == testString[i-1]) {
var testStringArray = testString.split(testString[i] + testString[i-1]);
testStringArray.sort(function(firstString, nextString){ return nextString.length - firstString.length})
returnString = testStringArray[0];
longestWithoutRepeat(testStringArray[0], returnString);
}
} else {
returnString = testString
}
}
return returnString;
}
console.log(longestWithoutRepeat("oolong"));
console.log(longestWithoutRepeat("google.com"));
console.log(longestWithoutRepeat("diddlyougotoofarout"));
I'm working on a project that has an input field requiring user to enter only any of the following three options:
Number like 150
Number starting with one letter (which must be N, not case sensitive) like N150
Number ending with one letter (which must be N, not case sensitive) like 150N
Any other value like:
150x will return error message wrong input
x150 will return wrong input
1N50 will return wrong position
The correct way to do this is to make an array of valid numbers and then to check if the given text exists on your array.For example:
var validNumbers = [ 150, N150, 150N ];
if (validNumbers.indexOf(parseInt(num, 10)) >=0 ) {
//Match
}
You'll need an indexOf function for IE:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
check this answer :
Regular expression to match a number range in JavaScript
and adjust to your needs, you can easily add the "N" at the end or at the beginning by adding regex part to make accept values like :
-N150
-150N
-130N
-N130
A non regexapproach (just to show why regex is useful):
function test(value){
//convert to array
value=value.split("");
//check the number
function isnumber(num){
return num.every(n=>"1234567890".includes(n));
}
//weve got three possibilities:
//150
if(isnumber(value)) return true;
//N150
var [n,...rest]=value;
if(n==="N" && isnumber(rest)) return true;
//150N
var n=value.pop();
return n==="N" && isnumber(value);
}
http://jsbin.com/kafivecedi/edit?console
I'm starting to learn javascript and I basically needed a countup that adds an x value to a number(which is 0) every 1 second. I adapted a few codes I found on the web and came up with this:
var d=0;
var delay=1000;
var y=750;
function countup() {
document.getElementById('burgers').firstChild.nodeValue=y+d;
d+=y;
setTimeout(function(){countup()},delay);
}
if(window.addEventListener){
window.addEventListener('load',countup,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',countup);
}
}
There's probably residual code there but it works as intended.
Now my next step was to divide the resultant string every 3 digits using a "," - basically 1050503 would become 1,050,503.
This is what I found and adapted from my research:
"number".match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
I just can't find a way to incorporate this code into the other. What should I use to replace the "number" part of this code?
The answer might be obvious but I've tried everything I knew without sucess.
Thanks in advance!
To use your match statement, you need to convert your number to a String.
Let's say you have 1234567.
var a = 1234567;
a = a + ""; //converts to string
alert(a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(","));
If you wish, you can wrap this into a function:
function baz(a) {
a = a + "";
return a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
}
Usage is baz(1234); and will return a string for y our.
While I do commend you for using a pattern matching algorithm, this would probably be easier to, practically speaking, implement using a basic string parsing function, as it doesn't look anywhere as intimidating from just looking at the match statement.
function foo(bar) {
charbar = (""+bar).split(""); //convert to a String
output = "";
for(x = 0; x < charbar.length; x++) { //work backwards from end of string
i = charbar.length - 1 - x; //our index
output = charbar[i] + output; //pre-pend the character to the output
if(x%3 == 2 && i > 0) { //every 3rd, we stick in a comma, except if it is not the leftmost digit
output = ',' + output;
}
}
return output;
}
Usage is basically foo(1234); which yields 1,234.
I have a user registration page,in which the mandatory fields are validated using java script.it works fine in all browsers and IE-8,9 but it's not working in IE-7.
The issue arises when validating password match.Below is requirement for pass word match
Pass word contain at least one number
Letters not repeat
it contain special characters.
Pass word must contain at least 6 letters.
Below is my code for validating the password match
function PasswordLenghtVal(pass) // validating pass word length
{
if(/\d/.test(pass) && pass.length >= 6)
{
return true;
}
return false;
}
function FirstNonRepeatedChar(str) //validating letters repeating or not
{
var i,j,repeated = 0;
var len = str.length;
for( i = 0; i < len-1; i++ )
{
repeated = 0;
if(str[i] == str[i+1] ) // checking for existing or not
{
repeated = 1;
break;
}
}
if( repeated == 0 )
return true;
else
return false;
}
This is code i have used for pass word match. Only problem in IE-7
The [] getter syntax for string is not available in IE7.
if(str[i] == str[i + 1]) // checking for existing or not
Change it with
if (str.charAt(i) == str.charAt(i+1))
And you can check it with regular expression:
function FirstNonRepeatedChar(str) {
return !/(.)\1/.test(str);
}
OK. First, you want to test each individual component in IE8 and IE7. Then, make it so that if its IE7 it uses something that works (Apparently the problem is str[] but as I do not use JavaScript very much I can't tell myself.) Just have a statement that redirects to a working piece of code if it's IE7 or below, and otherwise it goes to what you have.
My idea (Not real code, just to demonstrate what I mean - As I said I don't sue JS much):
if(browser = "IE7") {
//Code that works in IE7
} else {
//Code that works in everything else
}
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().