First of all apologise for creating my third Javascript question in as many days - I'm really trying to push myself in this field on this project, and feel my skills are developing at a fairly good rate thanks to my research and your fantastic help on here, particularly redsuqare!!
I've got a table where people can enter times, and have a mask in place where it'll check that the input is in the format 99:99 - which is great, but ideally I want to limit it to be no more than 23:59!
Here's the code I have at the moment, cobbled together the best I can, but unsurprisingly doesn't work...
$.each($('#hoursavailable tr td :checkbox'), function() {
var $this = $(elem); // cache the object
var $row = $this.closest('tr'); // find the nearest table row
if($this.is(':checked')) {
// do nothing!
} else {
$row.each(':text'),function() {
var splittime = $(this).split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
}
}
});
Could also be worth noting that there are two inputs per row/tr - it'd be absolutely ideal if I could somehow compare the two, to ensure that the first one is before the second, but appreciate that could be even more beyond me than the current stuff :(
Thanks
This may be what you are looking for-
http://www.the-art-of-web.com/javascript/validate-date/
I think all you need is the following change since your doing an each around the text inputs so you need to get the value out and split that.
$row.find(':text').each(function() {
var splittime = $(this).val().split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
});
However to save yourself re-inventing the wheel why not look into the validate plugin where you can configure regex expressions to deal with data validation.
Although I do appreciate hand rolling is also a good learning curve.
You're going mad with your eaches when you really only need one
This ought to get you going with a few caveats as detailed below.
$("#hoursavailable :checked").each(function() {
var splittime = $(this).parents("tr").find(":text").val().split(":");
if (splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date');
return false;
}
});
I've assumed here that you only have one text box (hence .find(":text") on the parent. You could consider adding a class, but bear in mind that class selectors are slow.
There is no validation here, so you might want to add a little more, however the premise works.
Synthesis from different methods to check for max & format together.
var timeFieldValue = $(this).val();
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if(timeFieldValue != '' && !timeFieldValue.match(re)) {
alert("Invalid time format: " + timeFieldValue);
$(this).focus();
return false;
}
var splittime = timeFieldValue.split(":");
if(splittime[0] > 23 || splittime[1] > 59) {
alert('Please enter a valid time');
return false;
}
Related
Alright, after digging through several sites...I am sure there is a better way to get the result I am looking for. Users are entering data in a text box on an HTML form and I want the format to change from 152000 (HHMMSS) to 15:20:00 (HH:MM:SS)
I was able to Frankenstein the jQuery below and it does work but I'm sure there is a better way to achieve the same result. I know I could handle the data after submission but would prefer to use jQuery to update it as they type. From what I read, I could use some type of time format but everything was focused on time as a date and I just need this to be a string that adds a colon after every two digits and limits the length to 8. Any thoughts?
$('#amount').keypress(function() {
// limits the charachters allowed
var regex = new RegExp("^[0-9:]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
//adds a colon after 2 digits typed
if(this.value.length == 2){
this.value = this.value+':';
}
//adds a colon after 5 character
if(this.value.length == 5){
this.value = this.value+':';
}
//limit to 8 total characters
if(this.value.length > 7) {
return false;
}
});
$('#amount').keypress(function() {
let $input = $(this);
let value = $input.val();
let update = value.replace(/(\d{2})(\d{2})(\d{2})/, '$1:$2:$3');
// 120000 --> 12:00:00
$input.val(update)
})
I am trying to format credit cards as users type them into the field. I've read every topic on the subject here on stack overflow, looked at tons of sites, lots of libraries and the code behind them. I want to create a simple function that will format credit cards as the user types them into the field using VANILLA JAVASCRIPT. Some of the following code comes from topics found here on Stack Overflow but none of the threads have solved the particular problem of doing this as the user is typing into the field.
PROBLEM: By default as the user is typing the into the given credit card field it changes the value by putting spaces in between the numbers, it will not validate as an American Express card until all the digits have been entered and thus not adjust the format until it is complete. I've tried casting the value without spaces and retesting it every cycle but to no avail.
function cc_format(v) {
//Strip the field value of spaces.
amextest = v.replace(/\s/g, '');
//Test if the card is an american express each cycle
if(/3[47]\d{2}[ -]*\d{6}[ -]*\d{5}/.test(amextest))
{
//This is some borrowed code to format american express cards - http://stackoverflow.com/questions/27322733/javascript-regex-format-string-containing-american-express-card-number
v.replace(/\b(\d{4})(\d{6})(\d{5})\b/, '$1-$2-$3');
return v;
}
else
{
//This properly formats every other card type as its being typed.
var v = v.replace(/[^\d]/g, '').match(/.{1,4}/g);
return v ? v.join(' ') : '';
}
}
//This binds the function to an input
document.getElementById('credit_card').oninput = function() {
this.value = cc_format(this.value)
}
I call upon the gods of stack overflow, please help me put this rest once and for all!
EDIT: Forgot the OP wanted plain JS. I'll leave this here for posterity, but it is obviously not an answer.
You could try this - match on the first two digits, and then automatically update the input after the 4th digit (and prevent an input greater than 17 characters (15 digits and 2 dashes):
$('#cc').on('keyup', function() {
var amexTest = $(this).val().replace(/ /g, '');
if (amexTest.match(/^3[47]\d{2}/)) {
if (amexTest.length == 4) {
amexTest += '-';
$('#cc').val(amexTest);
}
if (amexTest.length == 11) {
amexTest += '-';
$('#cc').val(amexTest);
}
if (amexTest.length > 17) {
val = $(this).val().substr(0, $(this).val().length - 1);
$(this).val(val);
}
} else {
if (amexTest.length > 16) {
val = $(this).val().substr(0, $(this).val().length - 1);
$(this).val(val);
}
if (amexTest.length == 16) {
var splits = amexTest.match(/\d{4}/g);
val = splits.join(' ');
$(this).val(val);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cc">
By reading other comments on this forum, I've put together a Submit button with JavaScript in Acrobat X that will email a certain person and include information from fields in the document in the Subject line and in the Body of the email. This part of the button works great and doesn't need changing.
Here's what I'm having trouble with: I want an error window to come up if the user hasn't completed all the Required fields (I've marked about 10 of them as Required), and I want this error to prevent that aforementioned email window from popping up. This actually works (with an IF/Else statement) in the code below, but the problem is that I don't want the error if a user enters "0" as a value. I want "0" to be seen as a real, non-empty field. As it is now, if a user enters "0" in any of the Required fields, it gives them the "Oops!" error, even though "0" could be a perfectly valid answer in this case.
I think the problem is with my "if (emptyFields.length>0)" statement or something in there, but I don't know how to correct it.
I'm sure this is an extremely obvious solution, but as a total JavaScript novice, it's eluding me. I've spent the last several hours looking at various comments, but I'm still not familiar enough with the JavaScript language to apply the information in those comments... Any help is appreciated.
var emptyFields = [];
for (var i=0; i<this.numFields; i++) {
var f= this.getField(this.getNthFieldName(i));
if (f.type!="button" && f.required ) {
if ((f.type=="text" && f.value=="") || (f.type=="checkbox" && f.value=="Off")) emptyFields.push(f.name);
}
}
if (emptyFields.length>0) {
app.alert("Oops! Please fill in the following field(s) before emailing:\n\n" + emptyFields.join("\n"));
} else {
var cToAddr = "emailaddress#company.com"
var cSubLine = "TD Submitted - " + this.getField("Store").value + ", SKU " + this.getField("SKU").value;
var cBody = "Hello,\n\n" + "Completed TDR attached."
+ "Thanks!\n\n"
+ this.getField("Name").value
this.mailDoc({
bUI: true,
cTo: cToAddr,
cSubject: cSubLine,
cMsg: cBody});
}
Thanks.
When you compare to "", javascript may cast the empty string to a number to compare. So when you check 0 == "", javascript converts the "" to a 0 and sees that they are equal. You can use === to avoid that conversion.
0 == ""; // true
0 === ""; // false
So your statement might be replaced with:
(f.type=="text" && f.value=="" && f.value !== 0)
This answer is much more detailed:
https://stackoverflow.com/a/359509/6083834
For the most part I have this code working. I originally had it so that if the email field length was greater than 10 then on keyup a div below would show. That worked okay. However, I want to add more validation. Below is my jQuery and I'm not sure I'm using the correct syntax.
$('#primaryemail').keyup(function(){
if($(this).val().length > 11 && ('#first_name').val().length > 6 && ('#phone_number').val().length == 10)
$('#projectinfo').show();
else
$('#projectinfo').hide();
});
I'm sure where I went wrong is with the && operators getting that from JavaScript and not entirely positive this is the correct way with jQuery.
Originally I had just the primaryemail as the validation but then added the first_name & phone_number as well. Once I added that it didn't work.
It might help to check your syntax and break it to multiple lines:
$('#primaryemail').keyup(function(){
if(
$(this).val().length > 11 // I suggest you also use .trim()
&& $('#first_name').val().length > 6
&& $('#phone_number').val().length == 10
) { // Always helpful to use Brackets
$('#projectinfo').show();
} else { // Especially around 'else'
$('#projectinfo').hide();
}
});
My suggested alternative is this:
// Cache your variables, noting the comma at the end of the first
// three lines, and the semicolon at the end of the 4th one.
// If you add more, use a comma after each one except the last one.
var $firstName = $('#first_name'),
$primaryEmail = $('#primary_email'),
$phoneNumber = $('#phone_number'),
$projectInfo = $('#projectinfo');
// Now bind your event listeners
// and use a simple function name to keep it easy!
$primaryEmail.keyup(function(){
if(isValidData()) {
$projectInfo.show();
} else {
$projectInfo.hide();
}
});
// Create a function for your logic that return a simple Boolean
// This keeps your state checking separate from your actions
// which rely on that state. You may check states in multiple places
// so it might be helpful to put them in separate functions to avoid
// repetition in the future.
function isValidData(){
return (
11 < $primaryEmail.val().trim().length
&& 6 < $firstName.val().trim().length
&& 10 == $phoneNumber.val().trim().length
);
}
I need to perform some validation using regular expressions in Javascript.
8 out of 10 of my regex validations work like a charm except this one, I have tried many changes in my regex and code, ran in firebug, dreamweaver, multiple browsers, the code will not alert, the problem lies in the function and i cannot point my finer on it.
here is a testing version of my code:
function validate_DOB()
{
var regexDOB = /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)([0-9]){4}$/i;
var checkDOB = "jan1888";//document.form.DateofBirth.value;
if (regexDOB.test(checkDOB) == false)
{
alert("Date of birth must be in the following format: jan1990(example)");
//document.form.DateofBirth.focus();
return false;
}
else if (2014 - eval(checkDOB.substr(3,4)) < 19)
{
alert("You must be at least 19 years of age");
//document.form.DateofBirth.focus();
return false;
}
else
{
alert("true");
return true;
}}// validate DOB
validate_DOB();
Any help is greatly appreciated, thank you.