Combining two simple scripts - javascript

How can I modify the script below so that it alerts not only when the field is empty, but when the field is empty or contains less than 10 digits (it can contain anything, not only digits)?
if (myform.mytextinput.value=="")
alert ('Please enter something!");
A good script that checks for ten digits is this:
var input_dg = document.getElementById("mytextinput");
var text_dg = input_dg.value;
var totalNrOfDigits = 0;
for(var i = 0; i < text_dg.length; i++){
if(/\d/.test(text_dg[i])){
totalNrOfDigits++;
}
}
alert ('Please enter at least 10 digits!');
I just need to "paste" the second script in the first, but I lack the know-how. Both scripts are inside a large form validation script...

Just use ||, the OR operator:
if (myform.mytextinput.value=="" || myform.mytextinput.length < 10)
To count the number of digits in a string I recommend this code (From this SO answer):
var totalNrOfDigits = myform.mytextinput.replace(/[^0-9]/g,"").length;
// And now combine both checks:
if (myform.mytextinput.value=="" || totalNrOfDigits < 10){
// Alert the user
}
If you want to use the same code you were using you only need to replace the first part:
var input_dg = document.getElementById("mytextinput");
var text_dg = input_dg.value;
var totalNrOfDigits = 0;
for(var i = 0; i < text_dg.length; i++){
if(/\d/.test(text_dg[i])){
totalNrOfDigits++;
}
}
if (myform.mytextinput.value=="" || totalNrOfDigits < 10){
// Alert the user
}

Try this using the OR(||):
if (myform.mytextinput.value=="" || myform.mytextinput.length < 10)

You can count them with a regex
var str ='1a2b3',
digits = (str).match(/\d+/g); // returns ["1", "2", "3"]
if ((! str.length) || (! digits) || (digits.length < 10)) {
alert ('Please enter at least 10 digits!');
}

Did you want this?
var input_dg = document.getElementById("mytextinput");
var text_dg = input_dg.value;
if(text_dg == "") {
alert ('Please enter something!');
} else if(text_dg.length < 10) {
alert("Please enter at least 10 digits!");
}
Fiddle.

Related

Adobe Javascript Calculation Errors

I want to check fields "Code1 to Code 32" for anything starting with "A" and ending with "B". I want the count to output to the field "Total1". I input the code under properties of "Total1" in the custom calculation. The Javascript doesn't calculate. What am I doing wrong?
var total = 0;
for (var i = 1; i <= 32; i++) {
var f = this.getField("Code" + i).valueAsString;
var v = f.valueAsString;
if (v.charAt(0) == "A" && v.charAt(v.length - 1) == "B") total++;
}
event.value = total;

javascript toLowerCase() function returns different string

console.log("HİNDİ".toLocaleLowerCase() == "hindi");
console.log("HİNDİ" == "hindi");
console.log("HİNDİ".toLowerCase());
console.log("HİNDİ".toLocaleLowerCase())
console.log("HİNDİ".toLowerCase())
I am building a search functionality but i come across a thing:
"HİNDİ".toLocaleLowerCase() // "hindi"
"hindi" == "HİNDİ".toLocaleLowerCase() //false
What the heck is going on here?
Solution:
#pmrotule's answer seems to work:
function to_lower(s)
{
var n = "";
for (var i = 0; i < s.length; i++) // do it for one character at a time
{
var c = s[i].toLowerCase();
// call replace() only if the character has a length > 1
// after toLowerCase()
n += c.length > 1 ? c[0].replace(/[^ -~]/g,'') : c;
}
return n;
}
Thanks,
It is a problem of string format. toLocaleLowerCase is meant for human-readable display only. However, there is still a trick you can do:
if ("hindi" == "HİNDİ".toLowerCase().replace(/[^ -~]/g,''))
{
alert("It works!");
}
EDIT
If you want to make it works with all special characters:
function to_lower(s)
{
var n = "";
for (var i = 0; i < s.length; i++) // do it for one character at a time
{
var c = s[i].toLowerCase();
// call replace() only if the character has a length > 1
// after toLowerCase()
n += c.length > 1 ? c.replace(/[^ -~]/g,'') : c;
}
return n;
}
console.log("gök" == to_lower("GÖK"));
console.log("hindi" == to_lower("HİNDİ"));
function to_low(s) // shorter version
{
var n = "";
for (var i = 0; i < s.length; i++)
{ n += s[i].toLowerCase()[0]; }
return n;
}
console.log("hindi" == to_low("HİNDİ"));
The problem is that your character İ is composed by 2 characters.
You have the I and then the 'dot' at the top (UTF-8 decimal code: 775).
Try this:
"HİNDİ".toLocaleLowerCase().split('').map((_,v)=>console.log(_.charCodeAt(0)))
Compare it with this:
"hindi".toLocaleLowerCase().split('').map((_,v)=>console.log(_.charCodeAt(0)))

Javascript password validation at least 2 number digits [duplicate]

This question already has answers here:
Regular Expression for password validation
(6 answers)
Closed 7 years ago.
I am trying to write a javascript validation for a password with the following criteria:
Password Must:
Have exactly 8 characters
Contain letters and numbers
Contain at least two numbers
EG:
"helloo15", "1helloo5" and "h1111111" are valid, "helloo1500", "27272727"and "helloos5" are invalid.
This is what I currently have:
//Password
var pw = document.myForm.password1.value;
var Vpw = /^[a-zA-Z0-9]{8}$/;
if (!Vpw.test(pw)) {
alert("Password must be 8 digits long. It must include a maximum of two numbers.");
return false;
} else {
/* alert("Valid CCV!"); */
}
But I can't figure out how to limit it to a minimum of 2 numbers anywhere in the string. Thanks!
try this one
var pass = "some44Passddword"; //document.myForm.password1.value;
var patt = new RegExp("^(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$");
if ( !patt.test(pass) )
{
alert("Password must be 8 digits long. It must include a maximum of two numbers.");
//return false;
}
else
{
alert("Valid!");
}
you can check this here: https://jsfiddle.net/esj9go59/
UPDATE
for also avoiding non-word characters like "$%#^&" you should use
^(?!(.*[^a-zA-Z0-9]){1,})(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$
regular expression.
Please notice that for some reason javascript test function does not respect \W as non-word characters and it is better to use [^a-zA-Z0-9] instead of this as stated in comment below
I know everyone has come through here and told you to use regular expressions (partly because you started with that). Please don't. There are times in which regular expressions are the better choice. That is rare though, they are way overused, and this is not one of those times. The following code is way more readable than the regex mess in the accepted answer.
This code also allows you to test each condition individually and give customized errors to the user.
function isValidPassword(str)
{
return str.length == 8 &&
digitCount(str) >= 2 &&
hasLetters(str) &&
hasOnlyLettersAndDigits(str);
}
function isAsciiCodeLetter(asciiCode)
{
return (65 <= asciiCode && asciiCode <= 90) ||
(97 <= asciiCode && asciiCode <= 122);
}
function isAsciiCodeDigit(asciiCode)
{
return 48 <= asciiCode && asciiCode <= 57;
}
function hasLetters(str)
{
for (var i = 0, len = str.length; i < len; i++)
{
if (isAsciiCodeLetter(str.charCodeAt(i)))
return true;
}
return false;
}
function hasOnlyLettersAndDigits(str)
{
for (var i = 0, len = str.length; i < len; i++)
{
var asciiCode = str.charCodeAt(i);
if (!isAsciiCodeLetter(str.charCodeAt(i)) &&
!isAsciiCodeDigit(str.charCodeAt(i)))
{
return false;
}
}
return true;
}
function digitCount(str)
{
var count = 0;
for (var i = 0, len = str.length; i < len; i++)
{
if (isAsciiCodeDigit(str.charCodeAt(i)))
{
count++;
}
}
return count;
}
Don't use regex, but if you're dead set on using regex, match on [0-9].*[0-9] for 2 digits, [a-zA-Z] for a character, and ^[0-9a-zA-Z]{8}$ for the length and characters/digits only requirement. That's at least sort of readable:
function isValidPassword(str)
{
var atLeastTwoDigits = new RegExp("[0-9].*[0-9]");
var atLeastOneCharacter = new RegExp("[a-zA-Z]");
var onlyEightCharactersAndDigits = new RegExp("^[0-9a-zA-Z]{8}$");
return atLeastTwoDigits.test(str) &&
atLeastOneCharacter.test(str) &&
onlyEightCharactersAndDigits.test(str);
}
Test cases:
alert(isValidPassword("asdfasdf")); //false
alert(isValidPassword("asdfasd4")); //false
alert(isValidPassword("7sdfasd4")); //true
alert(isValidPassword("asdfas`f")); //false
alert(isValidPassword("asd3a4df-")); //false
alert(isValidPassword("asd3a4f-")); //false
alert(isValidPassword("asd3a4df")); //true
alert(isValidPassword("12345678")); //false
alert(isValidPassword("1helloo5")); //true
alert(isValidPassword("helloos5")); //false
alert(isValidPassword("45345345")); //false
alert(isValidPassword("123`567d")); //false
You can use another regex for that:
//This will yield FALSE (as you expect)
var pw = "1jkj3kjlkj3"
alert(pw.replace(/[^0-9]/g,"").length >= 2)
You can create a function or add that into your if.

how to validate character and number in one textbox in javascript

The max size of textbox is given as 11. I want to print first 4 characters as alphabets and next 7 characters as numbers. Please give me a solution in javascript only.
function Myfunction2() {
var x2 = document.getElementById('text').value;
var re = /^[A-za-z]+$/;
for (i = 0; i < 4; i++) {
y = x2charAt(i);
if (re.test(x2.value)) {
alert("please enter char only");
}
}
}
function Myfunction() {
var x = document.getElementById("text").value;
for (i = 5; i < 11; i++) {
y = x.charAt(i);
if (y == " " || isNaN(y)) {
alert("not numeric");
}
}
}
Test it against an expected pattern:
/^[a-z]{4}[0-9]{7}$/i.test(value);
You could bind this to the actual input element as well to test it with each keystroke:
​var supercode = document.getElementById("supercode"),
rePattern = /^[a-z]{4}[0-9]{7}$/i;
supercode.addEventListener("keyup", function(e){
this.style.borderColor = rePattern.test(this.value) ? "green" : "red" ;
}, false);
Demo: http://jsfiddle.net/RfMK7/

How do I check if an input contains an isbn using javascript

I need a script that will test an input field's contents to see if it contains an ISBN. I found a few examples of this, but none of them strip the dashes. I need this to happen or my search results don't work. I have the else part of the script working if the field doesn't have an ISBN, but can't get the ISBN test to work. Thank you in advance for any help!
function search() {
var textboxdata = $('#search').val();
if (textboxdata contains an ISBN number, strip it of dashes and) {
// perform ISBN search
document.location.href = "http://myurl?search=" + textboxdata;
}
else { //perform other search
}
}
Based on the algorithms given in the Wikipedia article, here's a simple javascript function for validating 10- and 13-digit ISBNs:
var isValidIsbn = function(str) {
var sum,
weight,
digit,
check,
i;
str = str.replace(/[^0-9X]/gi, '');
if (str.length != 10 && str.length != 13) {
return false;
}
if (str.length == 13) {
sum = 0;
for (i = 0; i < 12; i++) {
digit = parseInt(str[i]);
if (i % 2 == 1) {
sum += 3*digit;
} else {
sum += digit;
}
}
check = (10 - (sum % 10)) % 10;
return (check == str[str.length-1]);
}
if (str.length == 10) {
weight = 10;
sum = 0;
for (i = 0; i < 9; i++) {
digit = parseInt(str[i]);
sum += weight*digit;
weight--;
}
check = (11 - (sum % 11)) % 11
if (check == 10) {
check = 'X';
}
return (check == str[str.length-1].toUpperCase());
}
}
There is also a js library available for checking ISBN10 and ISBN13 formatting: isbnjs as well as isbn-verify
Edit 2/2/17 - previous link was to Google Code, some updated current links:
- npm for isbn-verify
- npm for isbnjs
- Github project
Take a look at this Wikipedia article:
http://en.wikipedia.org/wiki/International_Standard_Book_Number
Should give you some insight into how to validate an ISBN number.
Derek's code fails for this ISBN ==> "0756603390"
It's because the check digit will end up as 11.
incorrect == > check = 11 - (sum % 11);
correct ==> check = (11 - (sum % 11)) %11;
I tested the new code against 500 ISBN10s.

Categories

Resources