0

I'm having issues with Javascript form validation for radio and checkboxes.

I have a external .js script with all my function rules linked in the html head section.

My rules look like this for example:

    function IsValid4DigitZip( str ) {
    // Return immediately if an invalid value was passed in
    if (str+"" == "undefined" || str+"" == "null" || str+"" == "")  
        return false;

    var isValid = true;

    str += "";

    // Rules: zipstr must be 5 characters long, and can only contain numbers from
   // 0 through 9
   if (IsBlank(str) || (str.length != 4) || !IsInt(str, false))
        isValid = false;

   return isValid;
} // end IsValid4DigitZip

And I call the function the section like this:

    if (IsValid4DigitZip(document.orderbooks.querySelectorAll("[name=postcode]")[0].value)) {

  } else {
    alert("Invalid postcode: You entered 3 or less digits. Please enter a 4 digit postcode");
    return false;
  }

Can some one help write function rules for radio and checkboxes using my examples.

I can only use Javascript. No Jquery.

Thank you.

c0nfus3d
  • 15
  • 3

2 Answers2

1

The first condition checks if str has a truthy value, the second checks for its length, and the last checks if all the characters are numbers.

P.S. I'm assuming the 5 in your Rules is a typo and you meant 4.

function isValid4DigitZip(str) {
 return str && str.length === 4 && /^\d+$/.test(str);
}

console.log(isValid4DigitZip('1234'));
console.log(isValid4DigitZip('124a'));
console.log(isValid4DigitZip('0000'));
console.log(isValid4DigitZip('12345'));
console.log(isValid4DigitZip('abcd'));
dork
  • 4,396
  • 2
  • 28
  • 56
0

In order to check whether the input inserted it string or not I recommend regex. The code above is good, but if you need to do another check, it will cause code duplication.

Do it like this:

var zipCodeRegex = /^\d+$/

function isValid4DigitZip(str) {
    return str && str.length === 4 && zipCodeRegex.test(str);
}

this way, it will be much easier to maintain and much more readable.

P.S. There is a wonderful site to test your regex conditions:

http://rubular.com/

Use it.

Barr J
  • 10,636
  • 1
  • 28
  • 46