Forms with Min Characters Requirement - javascript

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.

Related

How to compare a number in if condition?

I wrote this code for the user to guess a password exactly 4 times but I am not able to compare the input with the pin, is the way I have compared here wrong? can I not compare the number directly? like
if (input !== 0704)
is it wrong if I'm writing the number directly like this? it works fine if I replace the number with a string.
let pin = 0704;
let count = 0;
for (i=1; i<=4; i++) {
let input = prompt('please make a guess');
if (input !== 0704 ) {
console.log('Sorry that was wrong');
count++;
}
else {
console.log('That was correct!')
break;
}
}
if by input you are meaning html input then you need to compare the value with a string since output of html input is in string format. Also note the preceding 0 in 0704 will be ignored. So in this case you can use 0704 as string and perform comparison
let pin = '0704';
let count = 0;
for (i = 1; i <= 4; i++) {
let input = prompt('please make a guess');
if (input !== pin) {
console.log('Sorry that was wrong');
count++;
} else {
console.log('That was correct!')
break;
}
}
With number, input 0704 / 000704 has same value.
It must be a "String".

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

Javascript form validation. Street Number. How to set accepted numbers to 1 but accept numbers 1-99999

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;
}

JavaScript phone number validation using charCodeAt

I'd like to validate a phone number input using JavaScript to allow only number input. I prefer not to use regex, so I wrote a function like this:
function numberTest(){
for(var i=0;i<phone_number.length;i++){
if(phone_number.charCodeAt(i) >= 48 && phone_number.charCodeAt(i) <=57){
return true;
}else{
return false;
}
}
}
However it does not work. Any ideas why?
This doesn't work because it returns true after the first valid character. Neither branch will get past the first character, so you need to only return if you find an invalid character. Otherwise, if you reach the end without finding an invalid characters, you can finally return true.
Something like:
function numberTest(phone_number) {
for (var i = 0; i < phone_number.length; i++) {
if (phone_number.charCodeAt(i) < 48 && phone_number.charCodeAt(i) > 57) {
return false;
}
}
return true;
}
// Test various values
var testData = ["1234", "12ab", "123451234512345", "a1234123", "123123123a"];
var output = document.getElementById("results");
testData.forEach(function(test) {
var next = document.createElement("li");
next.textContent = numberTest(test);
});
<ul id="results"></ul>
The isNaN() (means is not a number) method will give you the reverted result in a simpler way...
var phone_number = "5511112223";
alert(isNaN(phone_number)); //returns false meaning it is a valid number
phone_number = "55aa1g11d12223";
alert(isNaN(phone_number)); //returns true meaning it is not a number

How to validate time using && in ajax

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

Categories

Resources