JavaScript Validation on Time Field (0:00 format not accepted) - javascript

Here is my code for validating incorrect time formats:
$('.allts').delegate(".tf", "focusout", function (e)
{
var curval = this.value;
curval = curval.replace(';', ':');
curval = curval.replace(" ", ':');
curval = curval.replace('.', ':');
//alert(curval);
if (/^\d$/.test(curval))
{
curval = "0" + curval + ":00";
}
if (/^[0-9]:[0-5][0-9]$/.test(curval))
{
curval = "0" + curval;
}
if (curval >= 10 && curval <= 12)
{
curval = curval + ":00";
}
if(curval.length==2&&curval >= 0 && curval <= 12){
curval = curval + ":00";
}
this.value = curval;
if (this.value != "")
{
if (!isValidDate(curval))
{
this.style.background = "#faa";
$('#msg_tformat').html('Please enter a valid time').show();
this.value = "";
}
My requirement is not to accept the 0:00 time format. If I give time formats like 0:00 it should display an error message like: "Please enter a valid time". Can anyone suggest the
proper way to validate for this in JavaScript?
Thanks in advance.

add to the isValidDate function something like this:
if( curval === '0:00' || curval === '00:00' ) {
return false;
}

Related

Making a date mask react with javascript: If i press simultaneous numbers i lost the mask

I'm trying to make a mask react date dd/mm/yyyy to a custom date input.
If i press the keys slow, the mask is setted correct dd/mm/yyyy, but supposing i press the numbers rapid, my mask is breaking
This is my component:
<DateInput
name="date"
placeholder="Data"
value={this.props.data}
dateFormat="DD/MM/YYYY"
onChange={this.props.changeDataTarefa}
animation="none"
onKeyUp={() => this.props.changeDataTarefaMask(this.fixDatePattern(this.props.data))}/>
this is my functions:
fixDatePattern(currDate) {
var currentDate = currDate;
if (currentDate){
var currentLength = currentDate.length;
var lastNumberEntered = currentDate[currentLength - 1];
}
if (!this.isNumber(lastNumberEntered) && currentDate) {
return currentDate.substring(0, currentLength - 1);
}
if (currentLength > 10) {
return currentDate.substring(0, 10);
}
let dateCountTracker = 0
if (currentLength == 1 && currentDate > 1) {
var transformedDate = "0" + currentDate + '/';
dateCountTracker = 2;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 4 && currentDate[3] > 3) {
let transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
dateCountTracker = 5;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
dateCountTracker = currentLength;
return currentDate + '/';
} else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
dateCountTracker = currentLength;
return currentDate + '/';
}
dateCountTracker = currentLength;
return currentDate;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Instead of using keyup, use keypress event on input. And you could also use react input mask plugin for same.
You can use below code for key press event and please check working stackblitz demo.
render() {
return (
<div>
<span>Date : </span>
<input type="text" maxLength="10" placeHolder="dd/mm/yyyy" onKeyPress={this.onKeyPress}/>
</div>
)
}
onKeyPress(e){
let input = e.target;
if(e.charCode < 47 || e.charCode > 57) {
e.preventDefault();
}
var len = input.value.length;
if(len !== 1 || len !== 3) {
if(e.charCode == 47) {
e.preventDefault();
}
}
if(len === 2) {
input.value += '/';
}
if(len === 5) {
input.value += '/';
}
}
You could use below react input mask plugins to achieve requirement.
imaskjs and react-input-mask

Phone Number Validation With Spacing

I have researched all over the place for a phone number validation in JavaScript that adds spacing as they type.
The closest code I came to was
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
while (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
newVal += val;
this.value = newVal;
});
http://jsfiddle.net/ssthil/nY2QT/.
Expect that is American Mobile Numbers. Anyone know how to do Australia format (XXXX XXX XXX). I tried moving the digits around in the JavaScript but nothing seemed to work.
Try this code :
while (val.length > 3) {
if(newVal.length > 4){
newVal += val.substr(0, 3) + ' ';
val = val.substr(3);
} else {
newVal += val.substr(0, 4) + ' ';
val = val.substr(4);
}
}
newVal += val;
this.value = newVal;
});
Working fiddle :
http://jsfiddle.net/nY2QT/718/
Modifying your code a little bit you can get something like this:
$('#ssn').on('input', function() {
var val = this.value.replace(/\D/g, '');
if(val.length > 10) {
this.value = this.value.slice(0,12);
} else {
this.value = (val.slice(0,4) + ' ' + val.slice(4,7) + ' ' + val.slice(7,10)).trim();
}
});
I have made some changes with loop hope it will works
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
var flag = true;
while (val.length > 3) {
if(flag){
flag=false;
newVal += val.substr(0, 4) + '-';
val = val.substr(4);
} else {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
}
newVal += val;
if(this.value.length >= 5){
this.value = newVal;
}
});
You could have instead three <input /> elements, give them each maxlength="4", maxlength="3", and maxlength="3" respectively. And as soon as the user completes each input, they're moved to the following:
HTML
<form>
<input maxlength="4" autofocus="autofocus" name="first"/>
-
<input maxlength="3" name="second"/>
-
<input maxlength="3" name="third"/>
</form>
Javascript/jQuery
// Autofocus second after first is complete
$('[name="first"]').keyup(function() {
if ( $(this).val().length == 4) {
$('[name="second"]').focus();
}
});
// Autofocus third after second is complete
$('[name="second"]').keyup(function() {
if ( $(this).val().length == 3) {
$('[name="third"]').focus();
}
});
// Alert numer after third is complete
$('[name="third"]').keyup(function() {
if ( $(this).val().length == 3) {
alert("Number: " + $('[name="first"]').val() + "-" + $('[name="second"]').val() + "-" + $('[name="third"]').val() + ".");
}
});
Also, to valide for only numbers, you can use RegEx:
// The following code is RegEx, used to validate the inputs so that the user can only type in numbers
$('[name="first"], [name="second"], [name="third"]').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
// Support for old browsers
$('[name="first"], [name="second"], [name="third"]').on('keyup', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
Eureka!
Edit: answer to Z-Dog's "question":
// Autofocus first if backspace is pressed and this is empty
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '8' && $(this).val().length == 0){
$('[name="first"]').focus();
// And delete last character
$('[name="first"]').val(
function(index, value){
return value.substr(0, value.length - 1);
});
return false;
}
Eureka 2.0!
Use Jquery Mask plug-in
https://igorescobar.github.io/jQuery-Mask-Plugin/
It simple to integrate ans use
Use this code it might work
document.getElementById('ssn').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/(\d{4}) ?(\d{3}) ?(\d{3})/,
'$1 $2 $3');
});

How to simulate back tab in textarea

I'm trying to simulate tabbing in a textarea, so far tab forward works but I'm not quite sure how to make backtab work. Any suggestions on how to do this, or better ways to do it would be helpful.
$('textarea').on('keydown mousedown', function(e){
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.shiftKey) {
console.log('shift')
if (e.which == 9 || e.keyCode == 9) {
console.log('shift + tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
} else if (e.which == 9 || e.keyCode == 9) {
console.log('tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
})
This might get you started.
$('textarea').on('keydown mousedown', function(e) {
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.which == 9 || e.keyCode == 9) {
e.preventDefault();
if (e.shiftKey) {
var firstTabPoint = val.lastIndexOf('\n', start) + 1;
if (val.substring(firstTabPoint, firstTabPoint + 1) == '\t') {
var startString = val.substr(0, firstTabPoint);
var endString = val.substr(firstTabPoint + 1);
this.value = startString + endString;
this.setSelectionRange(start - 1, end - 1);
}
} else {
this.value = val.substring(0, start) + '\t' + val.substring(end);
this.setSelectionRange(start + 1, end + 1);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="20" cols="100">
Add some lines in here, tab them, and then try untabbing.
</textarea>
As a side note, you might look into the attribute contenteditable="true" if you are making a text editor application.

How to make this validation work on cloned inputs

I have this id validation field, i just need to know how i can make the validation and the keydown and keyup functions work on cloned inputs. also inserted data is carrying over to the duplicate fields.
js fiddle- http://www.jsfiddle.net/dawidvdh/xRh9v/
Heres the js:
$(document).ready(function() {
idAmount = [0,1,2,3,4,5,6,7,8,9,10,12,13];
var idinc =1;
var id_val;
jQuery(idAmount).each(function() {
var index = "id"+idinc++;
var id_input = "<input class='id' id="+'"'+index+'"'+" "+" maxlength='1' />";
id_val = $(this).attr('value');
jQuery(id_input).appendTo('#id');
});
$("#clone").click(function () {
var clonedObj=$('#id').clone().insertAfter("#id");
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
});
});
function Validate() {
jQuery('#error p').remove();
var id_val = '';
$('.id').each(function(){ id_val+=($(this).val());});
var idNumber = id_val;
console.log(id_val);
var correct = true;
if (idNumber.length != 13 || !isNumber(idNumber)) {
correct = false;
}
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
console.log(tempDate);
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var currentYear = (new Date).getFullYear();
var age = currentYear - id_year;
var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
correct = false;
};
// if no error found, hide the error message
if (correct) {
jQuery('.id').css("border","1px solid #9A8B7D");
// clear the result div
jQuery('#result').empty();
// and put together a result message
jQuery('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p><p>AGE: ' + age + '</p>');
jQuery('#status').html("correct");
}
// otherwise, show the error
else {
jQuery('.id').css("border","1px solid #FF0000");
jQuery('#status').html("incorrect")
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('input.id').keydown(function(e){
if(e.keyCode == 8){
$(this).val('');
$(this).prev().val('');
$(this).prev().focus();
Validate()
}
});
$('input.id').on('keyup', function(){
if (this.value.match(/\d+/)) {
var $this = $(this);
if ($this.next('input').length) {
$this.next().focus();
} else {
Validate()
}
}
});
$(".id").keydown(function(event) {
// Allow: backspace, delete, tab, escape, and enter
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
});
HTML:
<div id="id">
<span id="label">ID NUMBER:</span>
<span id="status"></span>
</div>
<button id="clone">clone</button>
<div id="result"> </div>
CSS:
#error {
color: red;
border: 1px solid red;
padding: 5px;
display: none;
}
#result {
padding: 20px;
}
.id {
width:16px;
height:16px;
border:1px solid #9A8B7D;
margin:0;
float:left;
text-align:center;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
font-size:11pt;
padding:2px;
}
#label {
float:left;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
line-height:18px;
font-size:11pt;
margin-right:10px;
}
The only time that I see you call Validate is here :
$('input.id').on('keyup', function(){
//code
});
and here
$('input.id').keydown(function(e){
//code
});
Which means that the issue is the event handler is not delegated to a static element
$(document).on('keyup', 'input.id', function(){
//code
});
$(document).on('keydown', 'input.id', function(){
//code
});
Binding it to the document will ensure that any dynamically created elements will have the same event delegated to them as any static elements of the same selector.
Forgot the last part.
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
this.value = ''; //simply add this to remove the value
});
Although, because you're using jQuery, you should try to stick to using jQuery.
clonedObj.find('.id').each(function(){
$(this).prop('id', 'id'+ idinc++).val(''); // chain the commands
});

Format a number to time like hh:mm

I have an iput field:
<input type="text" name="time" class="time" value="3" />
I need that value to be like 03:00
More examples of what I need:
1 = 01:00
12 = 12:00
12:2 = 12:20
2:2 = 02:20
02:2 = 02:20
340 = 340:00
340:1 = 340:10
You know the rest. How can I solve this in jquery/javascript?
This is what I try in jQuery:
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
}
});
}
This is what I have made now and it does the job, but it is somewhat bulky :)
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
tid = (tid.length == 1) ? '0' + tid : tid;
tid = (tid.indexOf(':') == -1) ? tid + ':00' : tid;
if(tid.indexOf(':') != -1){
var arr = tid.split(':');
var before = arr[0].toString();
var after = arr[1].toString();
before = (before.length == 0) ? '00' : before;
before = (before.length == 1) ? '0' + before : before;
after = (after.length == 0) ? '00' : after;
after = (after.length == 1) ? after + '0' : after;
console.log('before: ' + before + ' After: ' + after);
tid = before + ':' + after;
}
}
$(this).val(tid);
});
}
You can do this with some simple regex:
function time( str ) {
if ( !/:/.test( str ) ) { str += ':00'; }
return str.replace(/^\d{1}:/, '0$&').replace(/:\d{1}$/, '$&0' );
}
If you want to make sure only the expected format is accepted, add this line at the top of the function:
if ( /[^:\d]/.test( str ) ) { return false; }
Demo: http://jsfiddle.net/elclanrs/MzgMz/
YOu can try something like this using datejs library:-
var dateString = "12";
var date = new Date.parseExact(dateString, "hh:mm");
check this DEMO
$('input').blur(timeFormat);
function timeFormat(e){
$("div").find('input').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
if(tid.indexOf(':') == 2){
$(this).val(tid.toString() + '0');
}
}
});
}​
<title>Insert Colon in the Time Format</title>
<script type="text/javascript">
function formatTime(objFormField){
intFieldLength = objFormField.value.length;
if(intFieldLength==2 || intFieldLength == 2){
objFormField.value = objFormField.value + ":";
return false;
}
}
</script>
Enter time <input type="text" maxlength="5" minlength="5" onKeyPress="formatTime(this)"/>
Pseudo:
val ← value from field ($('.time').val())
colonPos ← position of . in val
If colonPos equals -1, result ← padZero(val) + ':00'
Else, result ← padZero(val[:colonPos]) + ':' + padZero(val[colonPos + 1:])
function prettyTime(t){
// will output a time providing leading zeros and minute field
// (doesn't need jQuery)
x=t.split(":");
for (var i=0; i<2; i++)
x[i] = (x[i]) ? Array(3-x[i].length).join('0') + x[i] : '00';
return x.join(":");
}
// --
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
$(this).val(function(i, v) { return prettyTime(v); })
});
}
Maybe u can try this plugin.. Worked for me
Usage Examples:
$("#tbPlain").timefield();
$("#tb12Hour").timefield({ 'hourFormat': '12'});
$("#tb24Hour").timefield({ 'hourFormat': '24'});
$("#tbWithInvalidHandler").timefield({
'hourFormat': '24',
'onError' : function(){
alert(this.value+' is not a valid time!');
this.style.backgroundColor='red';
}
});
$("#tbOnOff").timefield();
$("#btnTurnOff").click(function(){
$("#tbOnOff").timefield('turnOffTimeField');
});
Live Example:
https://jsfiddle.net/sajjansarkar/bst3cw2g/

Categories

Resources