2

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...

chris97ong
  • 6,870
  • 7
  • 32
  • 52
Malasorte
  • 1,153
  • 7
  • 21
  • 45

4 Answers4

5

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
}
Community
  • 1
  • 1
aurbano
  • 3,324
  • 1
  • 25
  • 39
2

Try this using the OR(||):

if (myform.mytextinput.value=="" || myform.mytextinput.length < 10)
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • This does not count how many digits are contained in the input. – axelduch Apr 09 '14 at 08:36
  • @aduch:- Yes thats true actually I focussed on the main part of the question which asks about combining the scripts. However the answer provided by aurbano is adding that detail(already upvoted that!)`myform.mytextinput.replace(/[^0-9]/g,"").length` – Rahul Tripathi Apr 09 '14 at 08:39
2

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!');
}
axelduch
  • 10,769
  • 2
  • 31
  • 50
1

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.

chris97ong
  • 6,870
  • 7
  • 32
  • 52