Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two simple scripts

Tags:

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

like image 888
Malasorte Avatar asked Apr 02 '26 06:04

Malasorte


2 Answers

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
}
like image 157
aurbano Avatar answered Apr 03 '26 20:04

aurbano


Try this using the OR(||):

if (myform.mytextinput.value=="" || myform.mytextinput.length < 10)
like image 30
Rahul Tripathi Avatar answered Apr 03 '26 19:04

Rahul Tripathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!