Javascript Form How to - Validate input text field value on blur event








Question

We would like to know how to validate input text field value on blur event.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function validatestr(id,max,min) {<!--from  ww  w.  ja v  a  2  s  .  c  om-->
    var maximum = parseInt(max);
    var minimum = parseInt(min);
    var div = document.getElementById(id+'_error');
    var x = document.getElementById(id);
    div.innerHTML = '';
    if (x.value == null || x.value == '') {
        div.innerHTML = 'Value must not be null!';
    }
    if (x.value.length > maximum || x.value.length < minimum) {
        div.innerHTML = 'Value must be between '+minimum+' and '+maximum+' chars!';
    }
}

</script>
</head>
<body>
  <input type="text" class="textbox" id="varchar" name="varchar"
    onblur="validatestr('varchar',100,10)">
  <div style="display: inline; color: #ff0000; font-weight: bold"
    id="varchar_error"></div>
</body>
</html>

The code above is rendered as follows: