Validation Restriction
by Pratik Bhoir
HTML
<div>allowfloat</div>
<input type="text" name="numeric" class='allowfloat'>
<br/>
<br/>
<div>allownumeric</div>
<input type="text" name="numeric" class='allownumeric'>
<br/>
<br/>
<div>allowalphanumeric</div>
<input type="text" name="numeric" class='allowalphanumeric'>
<br/>
<br/>
<br/>
<div>Float</div>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed (With Decimal Point)</div>
<br/>
<div>Int</div>
<input type="text" name="numeric" class='allownumericwithoutdecimal'>
<div>Numeric values only allowed (Without Decimal Point)</div>
<br/>
<div>File Validation</div>
<input type='file' id='fileSize'>
CSS
.input-validation-error {
border: 1px solid #f00 !important;
background-color: #F8E0E0 !important;
}
JavaScript
// For float Validation
$(".allowfloat").on('keypress', function (event) {
if ((event.which != 46 || this.value.indexOf('.') != -1) && (event.which < 48 || event.which > 57)) event.preventDefault();
});
// for auto formating of float by parseFloat
$(".allowfloat").on('focusout', function (event) {
var temp = parseFloat(this.value);
if (isNaN(temp)) this.value = 0;
else this.value = temp;
});
//for Int Validation
$(".allownumeric").on('keypress', function (event) {
if ((event.which < 48 || event.which > 57)) event.preventDefault();
});
// for auto formating of Int by parseInt
$(".allownumeric").on('focusout', function (event) {
var temp = parseInt(this.value);
if (isNaN(temp)) this.value = 0;
else this.value = temp;
});
//for Int Validation
$(".allowalphanumeric").on('keypress', function (event) {
if ((event.which >= 48 && event.which <= 57) || (event.which <=95 && event.which >=45 )|| (event.which <=122 && event.which >= 97))
{
}
else
{
event.preventDefault();
}
});
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
//this.value = this.value.replace(/[^0-9\.]/g,'');
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
$(".allownumericwithoutdecimal").on("keypress keyup blur", function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
//function for fileSize
$('#fileSize').bind('change', function () {
var fileSize = this.files[0].size / 1024 / 1024;
if (fileSize > 3) {
$(this).addClass("input-validation-error");
alert("The file size is greater than 3MB");
} else {
$(this).removeClass("input-validation-error");
}
});