I'm working with a time validation and I'm confused on how to validate this start_time and end_time using &&. I have this code so far:
var re = /^(\d{1,2}):(\d{2})([ap]m)?$/;
//Start Time
if($('.start_time').val() != '') {
if(regs = $('.start_time').val().match(re)) {
if(regs[3]) {
// 12-hour value between 1 and 12
if(regs[1] < 1 || regs[1] > 12) {
$('.start_time_error').html('<div>Invalid value for hour(s)</div>');
$('.start_time').focus();
return false;
}
} else {
if(regs[1] > 12){
$('.start_time_error').html('<div>Invalid value for hour(s)</div>');
return false;
}
}
// minute value between 0 and 59
if(regs[2] > 59) {
$('.start_time_error').html('<div>Invalid value for minute(s)</div>');
$('.start_time').val().focus();
return false;
}
} else {
$('.start_time_error').html('<div>Invalid time format</div>');
$('.start_time').focus();
return false;
}
$('.start_time_error').html('<div>Checked</div>');
return true;
}else{
$('.start_time_error').html('<div>Please fill up</div>');
return false;
}
//End time----------
if($('.end_time').val() != '') {
if(regs = $('.end_time').val().match(re)) {
if(regs[3]) {
// 12-hour value between 1 and 12
if(regs[1] < 1 || regs[1] > 12) {
$('.end_time_error').html('<div>Invalid value for hour(s)</div>');
$('.end_time').focus();
return false;
}
} else {
if(regs[1] > 12){
$('.end_time_error').html('<div>Invalid value for hour(s)</div>');
return false;
}
}
// minute value between 0 and 59
if(regs[2] > 59) {
$('.end_time_error').html('<div>Invalid value for minute(s)</div>');
$('.end_time').val().focus();
return false;
}
} else {
$('.end_time_error').html('<div>Invalid time format</div>');
$('.end_time').focus();
return false;
}
$('.end_time_error').html('<div>Checked</div>');
return true;
}else{
$('.end_time_error').html('<div>Please fill up</div>');
return false;
}
I tried something like:
if(regs = $('.start_time').val().match(re) && regss == $('.end_time').val().match(re) )
But didn't work for me it sends and error regss is not defined. Any alternatives on how to do it? Thanks!
I think you're complicating things... Think about separation of concerns. In your logic you have 2 main blocks, the validation for the time string, and the DOM manipulation to extract those values and print the error. In your current code you're repeating the same logic twice for two fields, why not abstract that into a function?
Then I think is not worth printing multiple errors, if the time is invalid, then say something like "you entered an invalid time" and let the user know the right format, with a placeholder in the input, or in the generic error message.
If you follow this advice you can probably reduce your code by a lot and make cleaner and easier to understand. Here's an example, I adapted the regex from this question:
function isTime(str) {
return /^([1-9]|1[012]):[0-5][0-9]\s*?(am|pm)$/i.test(str);
}
Now you can validate your inputs like so:
var start = $.trim($('.start_time').val())
, end = $.trim($('.end_time').val());
if (!isTime(start) || !isTime(end)) {
$('.generic_error').html('<div>Please enter a valid time (HH:MM AM/PM)</div>');
}
Not sure about your HMTL but this should give an overall idea on how to abstract your code to make it DRY (Don't Repeat Yourself).
Demo: http://jsbin.com/ayAbUyI/1/edit
Related
I want if phone number starts with + it should accept 12 digits if it does not contain + it should accept 10 digit what changes I have to do?
My code is attached below.
function phvalid()
{
var a = document.getElementById('phone').value;
var gb = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (a=="") {
document.getElementById('ph').innerHTML="Enter Number";
}
if (a.match(gb))
{
document.getElementById("ph").innerHTML="";
// return true;
}
if(a.length!=10)
{
document.getElementById("ph").innerHTML="Enter 10 digits";
return false;
}
if(a.indexOf("+")==0)
{
document.getElementById("ph").innerHTML="Enter 12 digits";
return false;
}
else
{
document.getElementById('ph').innerHTML="";
}
}
Hope this will help you..!! I have used the simple startwith method.
function phoneValidator() {
var number = document.getElementById('phoneNumber').value
if(number.startsWith("+")) {
document.getElementById("phoneNumber").maxLength = 12;
}
else {
document.getElementById("phoneNumber").maxLength = 10;
}
}
<input type="text" name="phoneNumber" id="phoneNumber" onkeyup="phoneValidator()"/>
Firstly, your check for 10 digits overrides your check for 12. What I would do is:
function phvalid()
{
let phone = document.getElementById('phone');
let regex = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (phone.value=="") {
phone.innerHTML="Enter Number";
}
if (phone.value.match(regex))
{
phone.value.innerHTML="";
// return true;
}
if ( phone.value.charAt(0) != '+' && phone.value.length != 12 ){
if ( phone.value.length != 10 ){
phone.innerHTML = "Please enter a valid phone number, it should be 10 digits unless it is international in which case it should be 12 prefixed by a +";
return;
} else {
// Do whatever you need to do for a 10 digit phone number
}
} else {
// Do whatever you need to do for a 12 digit number
}
}
It is always easier to read your code later if you explain what you are doing, to yourself. The nested if, yes you could do it all on one line or use an iif there but when you come back to read it later, this will probably be easier to understand. I also set the result of the document.getElementById to a variable for both less typing and to make it clear what you are modifying. Your code you are modifying a different element. If that's what you are trying to do, it is still easier than calling getElementById every time you wish to modify it, calling and storing it means you only have to change it in one place if your code changes later instead of having a weird bug because you forgot to change it somewhere.
If I'm reading your regex right, the 10 digit phone number must start with a 0? It might be better to use:
let regex=/(^\+?\d{10,12}$)/;
I'm having trouble with some JS form validation.
I've linked a external .JS script in my html head section with function rules.
I have the following function rule in the .JS script file:
function IsValid5DigitStreetNumber( str ) {
// Return immediately if an invalid value was passed in
if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
return false;
var isValid = true;
str += "";
// Rules: zipstr must be 5 characters long, and can only contain numbers from
// 0 through 9
if (IsBlank(str) || (str.length != 1) || !IsInt(str, false))
isValid = false;
return isValid;
}
I have the following JS code in my html head section
if(IsValid5DigitStreetNumber(document.orderbooks.querySelectorAll("[name=streetnumber]")[0].value)) {
} else {
alert("Street Name invalid! Please enter a valid 1-99999 digit street number!:");
return false;
}
It's throwing up the alert message every time even when I enter a correct number.
I want to be able to accept a number between 1 and 99999 in the html form for street number. What do I change to get it working?
Edited:
After determining requirements at last:
function IsValid5DigitStreetNumber( str ) {
if (!/^\d{1,5}$/.test(str)) {
return false;
}
const num = parseInt(str, 10);
return num >= 1 && num < 1e5;
}
I have the following Validate form that request that a person completes all the relevant blocks on the form. I am trying to have one Block have a min number of characters for that specific block only. Below is my current code
<script>
function validateForm()
{
var a=document.forms["lbs_trace"]["lbs_reason"].value;
var b=document.forms["lbs_trace"]["lbs_for"].value;
var c=document.forms["lbs_trace"]["lbs_type"].value;
var x=document.forms["lbs_trace"]["lbs_case"].value;
var y=document.forms["lbs_trace"]["lbs_terms"].value;
var count = 0;
if (!(a==null|| a==""))
{
count++;
}
if (!(b==null|| b==""))
{
count++;
}
if (!(c==null|| c==""))
{
count++;
}
if (!(x==null || x==""))
{
count++;
}
if (!(y==null || y==""))
{
count++;
}
if(count < 5){
alert("Please assure that the following has been completed, CASE TYPE, REQUESTED BY, DESCRIPTION, CASE NUMBER and TERMS AND CONDITIONS ARE TICKED");
return false;
}
}
</script>
In VAR A I want a min of 30 Characters to be entered before continuing to process the form
Maybe use a javascript tag, this isn't php. Here's how to validate length:
if (!(a==null || a.length < 30))
You can simply write a code like this:
var lbs_reason = document.forms["lbs_trace"]["lbs_reason"].value;
var lbs_for = document.forms["lbs_trace"]["lbs_for"].value;
if(lbs_reason == null || lbs_reason.length < 30 || lbs_for == null || lbs_for == "")
{
// form not valid
}
You must do the same validations server-side, in PHP. Because Javascript may not be executed on the client and it's easy to craft HTTP requests.
<button onclick="isleap(1992)">Try it</button>
function isleap(year);
{
var yr=document.getElementById("year").value;
if ((parseInt(yr)%4) == 0)
{
if (parseInt(yr)%100 == 0)
{
if (parseInt(yr)%400 != 0)
{
alert("Not Leap");
return "false";
}
if (parseInt(yr)%400 == 0)
{
alert("Leap");
return "true";
}
}
if (parseInt(yr)%100 != 0)
{
alert("Leap");
return "true";
}
}
if ((parseInt(yr)%4) != 0)
{
alert("Not Leap");
return "false";
}
}
http://jsfiddle.net/kcyCd/
Having problems figuring out how to get the code to popup the alert box with the answer to the leap year.
A simple isLeapYear function is:
function isLeapYear(year) {
var d = new Date(year, 1, 29);
return d.getMonth() == 1;
}
It just sees if 29 February occurs in the given year. You should be able to do:
function isLeapYear2(year) {
return !!Date.parse(year + '-02-29');
}
on the basis that parsing an invalid date should return NaN, which type-converts to false, but not all browsers correctly implement Date.parse. e.g.
isLeapYear2('2001'); // false in Firefox, true in IE
<button onclick="alert(isleap(1992));">Try it</button>
If you alert the value returned from the isleap function it should work. I'm not guaranteeing the answer that pops up will be correct though.
Your fiddle doesn't work because you've kept the default jsfiddle setting that places your JS in an onload handler, which means your function isn't global and isn't accessible from the inline onclick attribute - this should be changed in the drop-down on the left to one of the "no wrap" settings. Also, the first thing the function would do if called is try to read the value from an element with id "year" and you have no such element. You currently ignore the year parameter.
Having said that, your function is way more complicated than it needs to be. You can greatly simplify your code by doing the parseInt() once at the beginning, then do whatever it is you need to do if the value being tested isn't an integer, and then you can do the leap year test in just one line.
Also, if you're using parseInt() on user input you must specify a radix as the second parameter if you want to avoid obscure bugs due to input starting with a leading zero being treated as octal. So parseInt(year, 10).
Finally, why return strings "true" and "false"? Wouldn't it make more sense to return actual booleans so that you can call your function as:
if (isleap(1992)) {
// do something
}
Anyway, here's a short version:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
if (year%4===0 && (year%100!=0 || year%400===0)) {
alert("Leap");
return true;
} else {
alert("Not leap");
return false;
}
}
Demo: http://jsfiddle.net/kcyCd/1/
If you didn't need to display the alert you could make it shorter still:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
return (year%4===0 && (year%100!=0 || year%400===0));
}
And obviously it would be a one-liner if you didn't need to test for invalid values.
You're passing a value into the function, and then looking for a different value in the DOM that doesn't exist.
Also, the code is hard to follow since you merged true/false conditionals, and you're using a string instead of a boolean - which is bad, because if(isleap(1992)) will always be true in your code.
Simplified:
function isleap(year)
{
if(year % 4 == 0 || (year % 100 == 0 && year % 400 == 0)){
return true;
}
return false;
}
I have an asp form which has a number of fields. On submit I want to check, using javascript that a tickbox has been selected and that an 'amount' field in within a given range AND has numbers only. I'm struggling to get it to check all three in one go - at the mometn i have the following:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if (x<5 || x >250)
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
At the moment this is two seperate checks for tick box select and range.
Any ideas appreciated.
Create a function that can do this:
function validate(str, chk, min, max) {
n = parseFloat(str);
return (chk && !isNaN(n) && n >= min && n <= max);
}
then call it like so:
function validateForm()
{
if(!validate(document.forms["myForm"]["Amount"].value,
document.forms["myForm"]["agreesubmit"].checked, 5, 250)) {
alert("Please complete all required fields - Amount you wish to save");
return false;
}
}
Try using the isNan(). Tutorial found at http://www.w3schools.com/jsref/jsref_isnan.asp
Something like:
if (isNaN(x) || x < 5 || x > 250))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
Quick note you might be confused about the or/ands, so notice that the x<5 || x >250 is wrapped in () so that it can be partnered with the and numeric condition. Then, finally the whole if wraps the statements.
This will ensure it has numbers only first, then check the number against a range.
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if( String(x).search(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/) != -1
&&( x<5 || x >250 ))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
via http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html