Javascript form validation. Radio buttons and checkboxes. How to validate?

0 votes
asked Sep 11, 2017 by c0nfus3d

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.

2 Answers

0 votes
answered Sep 11, 2017 by dork

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'));
0 votes
answered Sep 11, 2017 by barr-j

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.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...