How to validate input using javascript

前端 未结 7 1722
说谎
说谎 2020-12-20 16:00


        
7条回答
  •  礼貌的吻别
    2020-12-20 16:38

    If you do not plan on using jQuery this should work.

    function validate() {
        for (var field in document.getElementsByTagName('input')) {
            if (isPriceField(field)) {
                field.value = field.value.trim();
                if (isNaN(parseFloat(field.value))) {
                    return alertAndFocus(field, "Please enter a valid price");
                }
            }               
        }
    
        return true;
    }
    
    function isPriceField(field) {
        return (field.name.substr(0, Math.min(5, field.name.length)) === 'price')
    }
    
    function alertAndFocus(field, message) {
        alert(message);
        field.focus();
        return false;
    }
    

提交回复
热议问题