简体   繁体   中英

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

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.

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.

PS 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')); 

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.

PS There is a wonderful site to test your regex conditions:

http://rubular.com/

Use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM