string validation in jquery/javascript as MM:ss not HH:MM:ss - javascript

i want to validate a certain string that a jquery function receives.
here's what i have made so far
var duration=$('#duration').val();
if(//string validation?) {
$('.alert-box').html('Please use the correct format');
}
the string format the i want is mm:ss (its a duration m for minutes and s for seconds)so if a user just enter m:ss or mm:s or if the user entered a single digit minute or second, it should be preceded by a zero like if its 9:00 then it should be 09:00.
this is the latest code i've tried and its still not validating
$('#btnAddTestCat').click(function () {
var code = "addTestCat";
var test_cat=$('#test_cat').val();
var duration=$('#duration').val();
var sub_cat=$('#sub_cat').val();
var e = $('.alert-box');
e.slideUp(300);
if(!(/[0-5][0-9]:[0-5][0-9]/g).test(duration)){
e.html('Please use the correct format!');
return false;
}
var dataString = 'test_cat=' + test_cat + '&duration=' + duration + '&sub_cat=' + sub_cat + '&code=' + code;
$.ajax({
type: "POST",
url: "controller/category_controller.php",
data: dataString,
cache: false,
success: function(result){
var result = $.trim(result);
if(result=='success'){
e.removeClass("alert");
e.addClass("info");
e.html('Category added!');
e.slideDown(300);
e.delay(500).slideUp(300);
}else{
e.removeClass("info");
e.addClass("alert");
e.html(result);
e.slideDown(300);
e.delay(500).slideUp(300);
}
}
});
});

Use this Regex : for mm:ss
if(!(/^(?:[0-5][0-9]):[0-5][0-9]$/).test(duration)){
$('.alert-box').html('Please use the correct format');
}
DEMO

<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Test</title>
<script src="/script/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$('#Submit').click(function(){
var val = $('#Input').val();
var validinput = true;
if(val.length!=5){
validinput = false;
}
for(var i=1; i<=val.length; i++){
if(i!=3 && !(isNumeric(val.substring(i-1,i)))){
validinput = false;
}else if(i==3 && val.substring(i-1,i)!=':'){
validinput = false;
}
}
if (!validinput){
alert(val+" does not match the format mm:ss. Please correct this issue before submitting the form.");
return false;
}else{
alert("It's correct!!");
}
});
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
</script>
</head>
<body>
<input type="text" id="Input" value="" /> Format = mm:ss
<br />
<button type="button" id="Submit">Submit</button>
</body>
</html>

Related

How to display timestamp on a website and terminate a session after a particular time?

So I have this code which displays the current timestamp(IST)
<?php echo date("D M d, Y "); ?> </b>
<body onload="digiclock()">
<div id="txt"></div>
<script>
function digiclock()
{
var d=new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
if(s==60)
{
s=0;
m+=1;
}
if(m==60)
{
m=0;
h+=1;
}
if(h==12)
{
h=0;
}
var t=h>=12?'PM':'AM';
document.getElementById('txt').innerHTML=h+":"+m+":"+s+" "+t;
var t=setTimeout(digiclock,500);
}
How to compress this code and how to use it calculate a time limit for terminate a session. For example, a person is playing quiz and the quiz should terminate after 5 minutes and generate the score based on the questions attempted.
Here is example how to use #rckrd's js code snippet with PHP script called by AJAX.
The example is very basic, just to demonstrate implementation logic.
You cann look for live demo here http://demo1.rrsoft.cz/
Download code here http://demo1.rrsoft.cz/test.zip
index.php with HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="startQuiz()">Start timer</button>
<div id="messages"></div>
<div id="timerView"></div>
<div id="quiz_body"></div>
<script src="ajax.js"></script>
</body>
</html>
ajax.js with needed functions (I used #rckrd snippet, because is a grat example how to use it with PHP)
// This function has call php script with quiz answer...
var doAnswer = function(number){
var response_value = $('[name="qr'+number+'"]').val();
var response_message = '"Quiz #' + number + ' has successfuly saved';
$('[name="qr'+number+'"]').prop( "disabled", true );
$.ajax({
url: '/answer.php',
type: 'POST',
async: true,
data: {
quiz: number,
value: response_value
},
success:function(response){
if(response === 'OK'){
$('#messages').html(response_message);
}
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// This function just call the php script to render all quiz questions...
var startQuiz = function(){
$.ajax({
url: '/quiz.php',
type: 'GET',
async: true,
data: {
started: true
},
success:function(response){
$('#quiz_body').html(response);
startTimer();
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// Arange elements over time limit
var gameOver = function(){
$('#header').html('Game over');
$('#list').hide();
}
// This function manage time limitation logic and is called when quiz has started...
var startTimer = function (){
var timeLeftInMillis = 1*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
The quiz.php called by AJAX:
<?php
// very easy list of quizes...
$quiz_template = '
<h1 id="header">Quiz started!</h1>
<ul id="list">
<li>
Quiz 1 text
<input type="text" name="qr1" size="5"/>
<button id="bt1" onclick="doAnswer(1)">Send answer</button>
</li>
<li>
Quiz 2 text
<input type="text" name="qr2" size="5"/>
<button id="bt2" onclick="doAnswer(2)">Send answer</button>
</li>
<li>
Quiz 3 text
<input type="text" name="qr3" size="5"/>
<button id="bt3" onclick="doAnswer(3)">Send answer</button>
</li>
<li>
Quiz 4 text
<input type="text" name="qr4" size="5"/>
<button id="bt4" onclick="doAnswer(4)">Send answer</button>
</li>
<li>
Quiz 5 text
<input type="text" name="qr5" size="5"/>
<button id="bt5" onclick="doAnswer(5)">Send answer</button>
</li>
</ul>
';
// ... and return it
if((bool) $_GET['started'] === true){
die($quiz_template);
}
And Finaly answer.php
<?php
if($_POST){
// grab all needed posted variables... THIS IS JUST FOR DEMO, BECAUSE IS UNSECURED
$quizNumber = $_POST['quiz'];
$quirAnswer = $_POST['value'];
// do quiz PHP logic here, save answer to DB etc...
// when php script runs without errors, just return OK
$error = false;
if($error === false){
die('OK');
}else{
die($someErrorMessage);
}
}
var gameOver = function(){
document.getElementById("timerView").innerHTML = 'Game over';
}
var startTimer = function (){
var timeLeftInMillis = 5*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
<button onclick="startTimer()">Start timer</button>
<div id="timerView"></div>
If you are open to use third part libraries then check out EasyTimer.js plugin, this will solve the issue.
https://albert-gonzalez.github.io/easytimer.js/
or
countdownjs: http://countdownjs.org/demo.html
This is impossible in php, the best way is use JavaScript/Ajax...

Why is `pieceOfText` undefined?

I am creating a little guessing game involving decrypting text, but there is a variable inside my JavaScript code that is not working correctly. This variable, called pieceOfText, is supposed to be equal to a random piece of text generated from an array of 3 pieces of encoded text. However, when I retrieve the value of said variable, it outputs undefined.
Here is the code I have now:
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
<!DOCTYPE html>
<html>
<HEAD>
<META CHARSET="UTF-8" />
<TITLE>Decryption Guessing Game</TITLE>
</HEAD>
<BODY>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<SCRIPT LANGUAGE="Javascript">
</SCRIPT>
</BODY>
</html>
The line commented out is possibly preventing my guessing game from running properly because pieceOfText is set to undefined. I was currently doing some debugging at the time when I found this out. One question I found with a similar dilemma was more oriented towards ECMAScript 6 (I'm not sure if I'm using that), and others I found weren't even related to JavaScript. So, what caused this and how can I fix it?
You wrote Math.random instead of Math.random() (you forgot to actually call the function):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Decryption Guessing Game</title>
</head>
<body>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<script>
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
</script>
</body>
</html>

how to calculate the time keydown to keyup

this is the code, but it's not work,where is wrong.
<input type="text" name ="name" place="">
<button disabled="disabled">click</button>
<script>
$(function(){
var i = 0;
$('input').keydown(function(event) {
i++;
var temp = i;
setTimeout(function(){
var rate = (i-temp);
console.log(rate);
if(rate--){
$('button').attr('disabled',true);
}else{
$('button').attr('disabled',false);
}
},1000)
});
});
thx so much for you guys help
You can use JavaScript storage which is similar to session variables:
<script>
window.onload = function () {
document.onkeydown=(function (event) {
if (localStorage["Count"] == null) {
localStorage["Count"] = 0;
}
else {
localStorage["Count"]++;
}
alert("The count is: " + localStorage["Count"]);
});
}
</script>
in jquery you can use the following code :
KeyDown :
$("input").keydown(function(){ // when user push the key
// do something !!
});
KeyUp :
$("input").keyup(function(){ // when user is not pushing key enymore
// do something !!
});
Calculate time between keydown and keyup:
timebetween = 0;
var count = null;
$("input").keydown(function(){
timebetween = 0;
count = setInterval(function(){
timebetween++;
}, 1);
});
$("input").keyup(function(){
clearInterval(count);
$("body").append("<br>Time between keydown and keyup is "+timebetween+"ms");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
You can try this it will give you time in miliseconds.
$(document).ready(function(){
var startTime = false, endTime;
$(window).keypress(function(){
if(!startTime){
startTime = $.now();
}
});
$(window).keyup(function(){
endTime = $.now();
var keyPressedTime = (endTime - startTime);
console.info('keyyyUpppp', keyPressedTime)
startTime = false;
});
});
you can use this :
<!DOCTYPE HTML>
<html>
<head>
<title>Js Project</title>
</head>
<body>
<input type="text" id="txt" />
<div id="label"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var time = 0; // pressing time
var pressed = 0; // key is pushed or not ?
var timer = setInterval(calculate, 10); // calculate time
$("#txt").keydown(function(){
pressed = 1;
});
$("#txt").keyup(function(){
pressed = 0;
$("#label").html("Pressing Time : "+time+" ms");
time = 0
});
function calculate() { // increase pressing time if key is pressed !!
if (pressed == 1) {
time += 1;
}
}
</script>
</body>
</html>

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

jQuery autoruns functions on change events when page is loaded

I have made a function that validates inputs with for different kind of strings. I am having serious issues with a few things. I call it on form submit and for each input on change. I have written my code below and then the calling of function. Thing is: when I call it on change and refresh the page, it automatically runs the validations on change when the page is loading and renders the errors.
var Val = {
'string': function(ident, req, regexp, offset, limit) {
var ele = $(document.getElementById(ident));
Val.errors = false;
if (!ele.val() && req == 1) {
alert('blank');
Val.errors = true;
$("#" + ident + "Error").html("This field cannot be empty.");
$("#" + ident + "Error").show("fast");
}else if ((ele.val().length <= offset || ele.val().length > limit) && Val.errors == false) {
alert('not long enough');
Val.errors = true;
$("#" + ident + "Error").html("This field must be between " + offset + " & " + limit + " charecters long");
$("#" + ident + "Error").show("fast");
}else if (regexp !== null) {
switch (regexp) {
case 'text':
var regEx = /^([a-zA-Z]+)$/g;
break;
case 'number':
var regEx = /^([0-9]+)$/g;
break;
case 'email':
var regEx = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/g;
break;
case 'date':
var regEx = /^([123]0|[012][1-9]|31)-(0[1-9]|1[012])-(19[0-9]{2}|2[0-9]{3})$/g;
break;
case 'alphanum':
var regEx = /^([a-zA-Z0-9_\-\.]+)$/g;
break;
default:
break;
}
if (!regEx.test(ele.val()) && Val.errors == false) {
alert('not valid');
Val.errors = true;
$("#" + ident + "Error").html("This field is not valid");
$("#" + ident + "Error").show("fast");
}
}
if (!Val.errors){
$("#" + ident + "Error").hide("fast");
}
},
'send': function() {
if (!Val.errors) {
$('#form').submit();
}
}
}
Calling of the function:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Validations</title>
<script type="text/javascript" language="JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript" src="js/gcui.lsat.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#send').click(function(){
checkEmail();
checkUsername();
Val.send();
});
$('#emailID').change(checkEmail());
$('#username').change(checkUsername());
function checkEmail(){
Val.string('email', 1, 'username', 10, 100);
}
function checkUsername(){
Val.string('username', 1, 'alphanum', 5, 15);
}
});
</script>
</head>
<body>
<form id="form" action="">
<input type="text" id="email" name="email" title="Email" />
<input type="text" id="username" name="username" title="Username" />
<input type="button" id="send" value="Submit" />
</form>
Email: <div id="emailError"></div><br/>
Username: <div id="usernameError"></div>
</body>
</html>
$('#emailID').change(checkEmail());
Means "Run checkEmail and pass the return value to the change method"
You want:
$('#emailID').change(checkEmail);
Meaning "Pass the checkEmail function to the change method"
In your $('#send').click(function(){ you do submit it two times. The first time when you do the validation and the second time when the button press is fired. Add the line Return False; just after the Val.send(); and you only get the forum to submit if there form are filled out correct

Categories

Resources