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

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this using the OR(||):

if (myform.mytextinput.value=="" || myform.mytextinput.length < 10)

2 Comments

This does not count how many digits are contained in the input.
@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
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!');
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.