简体   繁体   中英

Input validation with Javascript in HTML5

What I'm looking for is a way to control input validation (HTML5) inside my Javascript functions, for now I have this:

function validate_select(combo){
    var index = combo.selectedIndex;

    if(index == 0){
        combo.setCustomValidity('Choose an element.');
        return false;
    }else{
        return true;
    }
}

if(validate_select(combo_product)){
    //do something and then reset combo
    combo_product.selectedIndex = 0;
}

Which work fine and just like I want, but I have some other elements (no form) and I want to trigger the validation just like the combo but instead of using some customValidity I want to use the HTML5 default validation. Any help is appreciate.

Is it possible or I'm just getting it to complex? (maybe a simpler alternative?)

I would like to get a non-jQuery solution, if possible.

<form action="" method="#">
  <select required="required">
     <option value="" selected> Please Select </option>
     <option value="1"> option 1 </option>
     <option value="2"> option 2 </option>
     <option value="3"> option 3 </option>
</select>
 <input type="submit" value="submit" />

http://jsfiddle.net/036easd8/

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