JavaScript error trapping is not reading 0 (zero) - javascript

The JavaScript below just checks if there are 4 digits in a field or not and then warns if there isn't.
But for some reason, if I enter four zeros (0000) it takes that as an empty field and throws the warning.
Any idea how to fix this...?? I am no programmer but have put this code together after weeks of trial-and-error.
function validate(){
// if ( (!isNaN($("#couponstart1").val())) || (!isNaN($("#couponstart2").val())) || (!isNaN($("#couponend1").val())) || (!isNaN($("#couponend2").val())) ) {
var all_ok = true;
var err_msg = "";
var fld = "";
if ( $("#couponstart1").val() == '' || $("#couponstart2").val() == '' || $("#couponend1").val() == '' || $("#couponend2").val() == '' ) {
all_ok = false;
err_msg += "\n - Card Numbers cannot be blank";
fld='couponstart1';
}else{
if ( isNaN($("#couponstart1").val()) || isNaN($("#couponstart2").val()) || isNaN($("#couponend1").val()) || isNaN($("#couponend2").val()) ) {
all_ok = false;
err_msg += "\n - Card Number has to be numeric";
fld='couponstart1';
}else{
if ( $("#couponstart1").val() < 1 || $("#couponstart2").val() < 1 || $("#couponend1").val() < 1 || $("#couponend2").val() < 1 ) {
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}else if ($("#couponstart1").val().length != 4 || $("#couponstart2").val().length != 4 || $("#couponend1").val().length != 4 || $("#couponend2").val().length < 4){
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}
}
}
if (all_ok == false){
alert("The following errors have taken place" + err_msg);
setFocus(fld);
}
return all_ok;
}

It's sad that computers do what we ask, not what we want.
If your input is filled with 0000, and you compare < it with the number 1: ($("#couponstart1").val() < 1, javascript will try to parse the value 0000 to the operand type which accounts to 0. So it is right to say that 0 is lower than 1and you'll get your error message Card number are not correct.
Let's try a different approach:
<!-- html -->
<form>
<p>
<label for="couponstart1">Coupon Start Part 1</label>
<input type="text" maxlength="4" id="couponstart1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start Part 2</label>
<input type="text" maxlength="4" id="couponstart2" class="validateme" />
</p>
<p>
<label for="couponend1">Coupon End Part 1</label>
<input type="text" maxlength="4" id="couponend1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start End 2</label>
<input type="text" maxlength="4" id="couponend2" class="validateme" />
</p>
<button type="button" id="testit">Test</button>
</form>
and:
/* javascript/jQuery */
$(document).ready(function(){
$("#testit").click(function(){
var rgx = /\d{4}/;
var allgood = true;
$("input.validateme").each(function(){
if( ! rgx.test( $(this).val() ) ){
alert("Card number for " + ($('label[for="' + $(this).attr("id") + '"]').text()) + " is not correct!\nPlease use 4 digits all numbers!");
$(this).select();
allgood = false;
return false;
}
});
if(allgood) alert("All good!");
});
});
Basically we have a form with 4 inputs with "validateme" class.
With jQuery we loop over the inputs that have this class an run it against the regex /\d{4}/ which basically will test for a number(\d) exactly 4 digits long ({4}) meaning from 0000 to 9999. Note that we use the label of the input to identify which field is not right.
Otherwise, all good.
You can fiddle with this code here: http://jsfiddle.net/L8dcgcrs/1/

Assuming the four digits correspond to $("#couponstart1").val(), $("#couponstart2").val(), $("#couponend1").val(), $("#couponend2").val() then the problem is that in JavaScript there are two types of comparison operators.
In your first if statement you choose to evaluate if $("#coupontstart1").val() == '' || ...). In this case you are using an equality operator which converts the operands if they are not the same type. So using this operator 0 == '' returns true. Instead you could use the strict equality operator === in the following manner:
if ( $("#couponstart1").val() === '' || ...)
In which case 0 === '' would return false. This most likely will help you in the first if statement you write as entering 0000 would make all the conditions false and you would proceed to the else block.
Hope this helps!

Related

Validation input field Fullname(Firstname,Lastname) - JavaScript

Need validation for full name(first name/last name - 1 input field). I'm new in this sphere and can't formulate the right syntax maybe will work with a regular expression too
<form name="myForm" action="#" id="form" onsubmit="return validateForm()" method="POST">
<div class="field"><span class="input"><i class="fas fa-user-alt"></i>
<input type="text" id="name" name="Fullname" placeholder="Full Name" >
</span>
function validateForm() {
var name= document.getElementById('name').value;
var x = name.indexOf(" ");
var fname = name.substring(0, x);
var lname = name.substring(x).trim();
if ( 17 < fname.value.length < 5 || 4 > lname.value.length > 17 || x.value.length != 1) {
alert("try again")
return false;
}
alert("OK")
return true;
}
The field (1 field) should contain 2 words which should be from 3 to 20 symbols.
EDIT:It seems work..finally!
function input (name) {
let fullNameArr = name.split('')
const space = ' '
let firstName = ''
if (fullNameArr.includes(space)) {
for (let i = 0; i < fullNameArr.length; i++) {
if (!firstName.includes(space)) {
firstName += fullNameArr[i]
}
}
}
firstName = fullNameArr.splice(0, firstName.length)
const lastName = fullNameArr
if (firstName.length > 3 && firstName.length <= 21 && lastName.length >= 3 && lastName.length <= 20 && lastName.includes(space) === false) {
console.log(firstName)
console.log(lastName)
} else {
console.log('Invalid Name')
return false
}
}
input('Todor Markov')
Your model makes several assumptions about names. Having first name and last name as separate input boxes is typically done to remove this barrier.
From a UX standpoint, if you were not going to have separate fields, you'd need some validation with a tooltip that checked if the user has more than one space that alerts them they must type FirstName LastName.
From a regex validation view, here's a catch all to ensure it's valid.
/^[a-z ,.'-]+$/i.test("Johnny 'Van' Pat-ton Jr.")
No numbers, but allow letters and the special characters ,.'-.

Prevent NaN from being pressed first or twice

I am building a calculator in JavaScript and want to prevent users from pressing a NaN (like divide, plus etc. i.e. only press a number first) and to prevent a Nan from being pressed twice e.g. don't allow divide to be pressed twice. How could I go about doing this?
Here is my code:
var result = ""; //must be a string so it concatenates rather than adds
function calc(digit){
if (digit == "ans"){
var prevResult = result;
result = prevResult;
$("#resultBox").append("Ans");
}
else if (digit == "sum"){
$("#resultBox").val(eval(result));
}
else if (digit == "clear"){
location.reload();
}
else{
result += digit;
$("#resultBox").val(result);
}
}
here is an example of a few buttons in my HTML:
<button class="large" type="button" value="divide"onclick=calc("/")>/</button>
<button class="small" type="button" value="1" onclick=calc(1)>1</button>
change first else section to
else if (digit == "sum"){
if ( result.length > 0 )
{
$("#resultBox").val(eval(result));
}
}
similarly, for divide and plus, check if the last character is a number
if ( result.length > 0 && !isNaN(result.slice(-1) )
{
result += digit;
}

How to get alerts for inputed name length of characters - javascript

Hello im trying to do a simple script here when i enter name in input field, i want to get certain alerts for example:
- if name is > 20 characters alert = "name is bigger than 20"
- if name is between 12 and 20 alert = exact number of chars of the name that was inputed
- if name is bigger than 2 chars and bigger or equal than 20 = alert that name
this was just an example of what im trying to do, but im just noob at this point im only 1 month into javascript(html and css) so if anyone can point me in the right direction i would appreciate.
Ok, so far i have this:
<form name="myForm" id="form2" onsubmit="return validate()">
Input name: <input type="text" name = "myName" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
function validate() {
if(document.myForm.myName.value.length>20){
alert("your name is too big");
submitFlag=false; // im not sure what this line does //
} else if(document.myForm.myName.value.length=12-20){
alert("your name is" + document.myForm.myName.value.length + " chars");
} else if(document.myForm.myName.value.length=0){
alert("input name")
}else{
alert("ok e")
}
return submitFlag;
}
THe if statements are workin only if i have two, im getting only the first 2 alerts, so i would like to input more else if statements and to get alerts for them also, i tried to put some more myself, but the dont work, im only getting the first two.
Extending what #dfsq have said,.. you try to get:
if name is between 12 and 20
that means smth like:
document.myForm.myName.value.length > 12 && document.myForm.myName.value.length <= 20
And make your code more simple and readable. And don't forget to return false (your submitFlag):
function validate() {
var len = document.myForm.myName.value.length;
if (len > 20)
{
alert("your name is too big");
}
else if (len > 12 && len <= 20)
{
alert("your name is" + len + " chars");
}
else if (len == 0)
{
alert("input name");
}
else
{
//in fact it would alert when name between 0 and 12
alert("ok e");
}
return false;
}
There are a difference between operators. = is an assignment, == and === are comparison operators. You need latter:
document.myForm.myName.value.length == 0
Here we go:
function validate() {
var charLength = document.myForm.myName.value.length,
submitFlag = false; // This flag would be used further to stop the use going ahead from this particular validation
if (charLength > 20) {
// length more than 20
alert("your name is too big");
} else if (charLength <= 20 && charLength > 12) {
// length between 20 and 12
alert("your name is" + charLength + " chars");
} else if (charLength == 0) {
// If no input there
alert("enter name");
} else {
// Otherwise in success condition
alert("ok e");
submitFlag = true;
}
return submitFlag;
}
Jsfiddle: http://jsfiddle.net/fcwbkkd7/

Mask input on html does not work

I'm trying to create a mask to my input, but one strange error happens. I have to enter 11 numbers, and my mask have to make it like this: ###.###.###-##. But when I enter the sixth digit my current input become blank. I have no idea what is the problem.
This is my script:
function mascararCpf(){
var cpf = document.getElementById("idCpf");
if((cpf.value.length == 3) || (cpf.value.length == 6)){
cpf.value += ".";
return;
}
if(cpf.value.length == 9){
cpf.value += "-";
return;
}
}
And this is my input:
<label> CPF: <input type="number" autocomplete="on" name="cpf" id="idCpf" placeholder="Seu CPF" required onblur="validarCpf()" onkeypress="mascararCpf()"></label>
Try with
<input type="text" ...
problem with the input type number
DEMO
If you want to open Numeric keypad on focus, I would suggest you to use
<input type="tel" ...
Another DEMO
That's because you need to count dots . as part of the length. "123.456" is SEVEN characters long.
It is a common practice to put several input fields (in your case 4 fields) and to go from one field to the other when the length of the field (3) has been reached.
As noted before the input type should be text. Furthermore, you should consider that the length of the input value increases after appending a '.' or '-'.
Your html is not valid. The <label>-tag should be closed before opening <input>.
It's better not to use inline handlers. You can assign your hander in the script. Using type="text" the input value can also be non numeric. If you want the mask-method to check that you should add checking of the inputted value. A tentative method could be:
// bind handler to the input field
document.querySelector('#idCpf').onkeypress = mascararCpf;
// the handler method, including a numeric-check for the entered value
function mascararCpf(e){
var len = String(this.value).length;
this.value += len === 3 || len === 7 ? '.' : len === 11 ? '-' : '';
return isNaN(+String.fromCharCode(e.keyCode)) ? false : true;
}
Here's a jsFiddle demonstrating it all
I had a similar need, so I developed the following code. Not 100% yet, but it works.
function editMask(mask,element,e) {
if (e.keyCode >= 48 & e.keyCode <= 57 | e.keyCode >= 96 & e.keyCode <= 105 | e.keyCode == 46 | e.keyCode == 8) {
var v = element.value;
var N = v.replace(/\D/g,'');
var L = N.length;
var r = '';
var resp = '';
for (i=0;i<mask.length;i++) {
if (mask[i] == '_') {
if (N.length > 0) {
r = N[0];
N = N.substring(1,N.length);
} else {
r = '_';
}
} else {
r = mask[i];
if (N.length > 0) {
L++;
}
}
resp = resp+r;
}
element.value = resp;
element.setSelectionRange(L,L);
}
}
It's called in the onkeyup event of the input:
<input type='text' size=20 id='insPFis_CPF' value='$CPF' onkeyup='javascript:editMask(\"___.___.___-__\",this,event)'>
You may want to change the mask format for CNPJ, phone numbers, etc. I hope it helps.

Preventing user to enter more numbers after 2 digits before decimal point

I'm having a problem with letting users enter numeric values in my textboxes which have the same class.
What I Want:
Allow users to enter only 2 numbers before the decimal points and another 2 after it; otherwise all keys are log except arrows keys, backspace, and delete key
Current Issue
Users can only enter 2 numbers; however, after he/she adds a decimal points, they can add more numbers before it
Currently, users can only enter 5 digits--2 before the decimal point, and another 2 after the decimal points. When they delete one digit after the decimal point, they can still add more number to digit before that decimal point.
My HTML:
<form method="post">
<div class="row">
<label>Val 1</label>
<input type="text" class="validate" name="val1" maxlength="5" />
</div>
<div class="row">
<label>Val 2</label>
<input type="text" class="validate" name="val2" maxlength="5" />
</div>
<div class="row">
<label>Val 3</label>
<input type="text" class="validate" name="val3" maxlength="5" />
</div>
<div class="row">
<button type="submit">Send</button>
</div>
</form>
My JS:
Number.prototype.between = function (a, b, inclusive) {
var min = Math.min.apply(Math, [a,b]),
max = Math.max.apply(Math, [a,b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
$('.validate').keypress( function( event ) {
var v = parseFloat($(this).val() + String.fromCharCode(event.which));
textValue = parseFloat(v).toString();
var newVal = parseInt( textValue.substr(0, textValue.indexOf(".")) );
console.log(newVal);
if(textValue.length < 6){
if(!parseFloat(v).between(0,99.99,true)) {
v = this.value.substring(0, 2);
$(this).val(v);
return false;
}
return true;
}
});
Here is the link to my fiddel DEMO
Try this :
<input type="text" class="validate" name="val1" maxlength="5" onkeypress="return CheckDecimalValues(event)" />
function CheckDecimalValues(evt) {
var keyCode = evt.keyCode ? evt.keyCode : ((evt.charCode) ? evt.charCode : evt.which);
// 8 Backspace
// 9 Tab key
// 46 Delete
// 35 End Key
// 36 Home Key
// 37 Left arrow Move
// 39 Right arrow Move
if (!(keyCode >= 48 && keyCode <= 57)) {
if (!(keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 39 || keyCode == 46)) {
return false;
}
else {
return true;
}
}
var velement = evt.target || evt.srcElement
var fstpart_val = velement.value;
var fstpart = velement.value.length;
if (fstpart .length == 2) return false;
var parts = velement.value.split('.');
if (parts[0].length >= 14) return false;
if (parts.length == 2 && parts[1].length >= 2) return false;
}
Why don't you use a regex to validate your requirement?
A simple regex like so:
[0-9]{1}[0-9]{1}[\.]{1}[0-9]{1}[0-9]{1}
can be used to validate the input without worrying about the key strokes. Just add an onblur event on your textbox to validate this.
EDIT:
I have added this Fiddle
Check it out.

Categories

Resources