GST number validatoin in jquery - javascript

I want to do GST validation in javascript or jquery
Its limited to india only.
the structure of GST in India is as follows
GST Number will be of 15 digits having below validations:
a. First two positions will be numeric
b. Third to Sixth positions will be Alphabets
c. Seventh position will be either alphabet or numeric
d. Eighth to Eleventh positions will be numeric
e. Twelfth position will be an alphabet
f. Thirteenth to Fifteenth positions will be alphanumeric

([0-9]{2}[a-z]{4}([a-z]{1}|[0-9]{1}).[0-9]{3}[a-z]([a-z]|[0-9]){3}) Here is the regex for GST validation
http://regexr.com/ Test your GSTvalues with the above regex.

Here is the regex for GST validation in JavaScript:
var reggst = /^([0-9]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([0-9]){1}([a-zA-Z]){1}([0-9]){1}?$/;
if(!reggst.test(gstinVal) && gstinVal!=''){
alert('GST Identification Number is not valid. It should be in this "11AAAAA1111Z1A1" format');
}

Finally i got GST validation regular expression with handle 15 digit only :)
/^([0-9]{2}[a-zA-Z]{4}([a-zA-Z]{1}|[0-9]{1})[0-9]{4}[a-zA-Z]{1}([a-zA-Z]|[0-9]){3}){0,15}$/

$('#gst').on('change', function () {
var statecode = $(this).val().substring(0, 2);
var pancarno = $(this).val().substring(2, 12);
var entityNumber = $(this).val().substring(12, 13);
var defaultZvalue = $(this).val().substring(13, 14);
var checksumdigit = $(this).val().substring(14, 15);
if ($(this).val().length != 15) {
alert('GST Number is invalid');
$(this).focus();
return false;
}
if (pancarno.length != 10) {
alert('GST number is invalid ');
$(this).focus();
return false;
}
if (defaultZvalue !== 'Z') {
alert('GST Number is invalid Z not in Entered Gst Number');
$(this).focus();
}
if ($.isNumeric(statecode)) {
$('#gst_state_code').val(statecode).trigger('change');
} else {
alert('Please Enter Valid State Code');
$(this).focus();
}
if ($.isNumeric(checksumdigit)) {
return true;
} else {
alert('GST number is invalid last character must be digit');
$(this).focus();
}
});

Regex for GSTIN validation
/^([0-2][0-9]|[3][0-7])[A-Z]{3}[ABCFGHLJPTK][A-Z]\d{4}[A-Z][A-Z0-9][Z][A-Z0-9]$/

let vGST = (gnumber)=>{
let gstVal = gnumber;
let eMMessage = "No Errors";
let statecode = gstVal.substring(0, 2);
let patternstatecode=/^[0-9]{2}$/
let threetoseven = gstVal.substring(2, 7);
let patternthreetoseven=/^[A-Z]{5}$/
let seventoten = gstVal.substring(7, 11);
let patternseventoten=/^[0-9]{4}$/
let Twelveth = gstVal.substring(11, 12);
let patternTwelveth=/^[A-Z]{1}$/
let Thirteen = gstVal.substring(12, 13);
let patternThirteen=/^[1-9A-Z]{1}$/
let fourteen = gstVal.substring(13, 14);
let patternfourteen=/^Z$/
let fifteen = gstVal.substring(14, 15);
let patternfifteen=/^[0-9A-Z]{1}$/
if (gstVal.length != 15) {
eMMessage = 'Length should be restricted to 15 digits and should not allow anything more or less';
}else if (!patternstatecode.test(statecode)) {
eMMessage = 'First two characters of GSTIN should be numbers';
}else if (!patternthreetoseven.test(threetoseven)) {
eMMessage = 'Third to seventh characters of GSTIN should be alphabets';
}else if (!patternseventoten.test(seventoten)) {
eMMessage = 'Eighth to Eleventh characters of GSTIN should be numbers';
}else if (!patternTwelveth.test(Twelveth)) {
eMMessage = 'Twelveth character of GSTIN should be alphabet';
}else if (!patternThirteen.test(Thirteen)) {
eMMessage = 'Thirteen characters of GSTIN can be either alphabet or numeric';
}else if (!patternfourteen.test(fourteen)) {
eMMessage = 'fourteen characters of GSTIN should be Z';
}else if (!patternfifteen.test(fifteen)) {
eMMessage = 'fifteen characters of GSTIN can be either alphabet or numeric';
}
console.log(eMMessage)
}
vGST("33");
vGST("12ABCDE1234K11S");
vGST("12ABCDE1234K1ZS");

var reggst = /^([0-9]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([0-9]){1}([a-zA-Z]){1}([0-9]){1}?$/;
if(!reggst.test(gstinVal) && gstinVal!='' && gstinval.length!=15){
alert('GST Identification Number is not valid. It should be in this "11AAAAA1111Z1A1" format');
}
You can simply get the length of the field value and compare it with the count that you want.

You can do that with a regular expression as follows
var regex = /^\d{2}\w{4}[a-zA-Z0-9]{1}\d{3}\w{1}[a-zA-Z0-9]{3}$/i;
if (regex.test('GSTNumber')) { console.log('valid'); }

Here is the regex for GST Number validation which validate for 15 alphanumeric characters :
var regex ="\d{2}[A-Z]{5}\d{4}[A-Z]{1}\d{1}[A-Z]{1}\d{1}"

Here is a regex code that i am currently using on my project for gst number validation.
^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9]{1}Z[a-zA-Z0-9]{1}$
thank you.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).on('change',".gstinnumber", function(){
var inputvalues = $(this).val();
var gstinformat = new RegExp('^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$');
if (gstinformat.test(inputvalues)) {
return true;
} else {
alert('Please Enter Valid GSTIN Number');
$(".gstinnumber").val('');
$(".gstinnumber").focus();
}
});
</script>

I use this functions in my code
function check_gst(gst){
if(gst.length != 15){
alert("Invalid Length of GSTIN");
return false;
}else{
var state = parseInt(gst.substring(0, 2));
// FIRST 2 CHARACTERS STATE CODE
if(state < 1 || state > 37){
alert("Invalid First Two Characters of GSTIN");
return false;
}
// NEXT 10 CHARACTERS PAN NO. VALIDATION
var pan = gst.substring(2, 12).toUpperCase();
var regex = /[a-zA-Z]{3}[PCHFATBLJG]{1}[a-zA-Z]{1}[0-9]{4}[a-zA-Z]{1}$/;
if( !regex.test(pan) ){
alert("Invalid GSTIN");
return false;
}
// DEFAULT 14TH CHARACTER 'Z'
var char14 = gst[13].toUpperCase();
if(char14 != "Z"){
alert("14th character of GSTIN should be 'Z'");
return false;
}
// CHECKSUM DIGIT
if(check_gst_checksum(gst.substring(0, 14)) != gst[14]){
alert("Invalid GSTIN");
return false;
}
return true;
}
}
String.prototype.getw = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
function check_gst_checksum(gst_wo){
weight_c = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
gst = gst_wo.toUpperCase();
var total_a1 = 0;
for (var i = 0; i < gst.length; i++) {
var weight = weight_c.getw(gst[i]);
var factor = ( (i % 2) +1 );
var product = weight * factor;
var qu = Math.floor( product/36 );
var re = product % 36;
var a1 = qu + re;
total_a1 += a1;
}
var d = total_a1 % 36;
var dd = 36 - d;
return weight_c[dd];
}
All the calculation for checksum digit is given at this blog
https://gauravj75.blogspot.in/2018/01/excel-gstin-checksum-digit-logic.html

It's too late to respond but someone will help this.
First two Digits-The first digit of GSTIN is state code as per Indian Census 2011. The state codes are as below.
01-Jammu and Kashmir, 02-Himachal Pradesh, 03-Punjab, 04-Chandigarh, 05-Uttarakhand, 06-Haryana, 07-Delhi, 08-Rajastan, 09-UP, 10-Bihar, 11-Sikkim, 12-Arunachal Pradesh, 13-Nagaland, 14-Manipur, 15-Mizoram, 16-Tripura, 17-Meghalaya, 18-Assam, 19-West Bengal, 20-Jharkhand, 21-Orrissa, 22-Chattisgarh, 23-MP, 24-Gujarat, 25-Daman and Diu, 26-Dadar and Nagar Haveli, 27-Maharashtra, 28-Andhra Pradesh, 29-Karnataka, 30-Goa, 31-Lakshadweep, 32-Kerala, 33-Tamil Nadu, 34-Puducherry and 35-Anadaman and Nicobar Islands.
Next 10 Digits-It is the PAN number of a business entity like your shop, mall or company.
13th Digit-It indicates the number of registrations as a business entity has within a state for the same PAN. It will be an alpha-numeric number (first 1-9 and then A-Z) and will be assigned on the basis of the number of registrations a legal entity (having the same PAN) has within one state.
Let say the company ABC registered in the same state for 5 times for different businesses. In such case, this digit will be printed as 5. Let us assume, the same company registered for around 15 times, then it should be represented as F (1-9 numeric and later on 10th registration be named as A and 11th as B and so on up to Z).
Hence, a business entity can register the GSTIN within a single state for the maximum of 35 times (1-9 and later on A-Z).
14th Digit-It will be by default as Z.
15th Digit-The last digit will be a check code which will be used for detection of errors.
With this information working RegEX is below
^[0-9]{2}[A-Za-z]{3}[CPHFATBLJGcphfatblj]{1}[A-Za-z]{1}[0-9]{4}[A-Za-z]{1}[0-9A-Za-z]{1}(Z|z)[0-9A-Za-z]{1}$
This is perfect GST Validation code.

This will definitely work with your jQuery.
rules: {
gst_number_value: {
required: true,
minlength: 15,
maxlength: 15,
pattern: '^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9]{1}[A-Z]{2}$',
},
},
messages: {
required: "Please enter GST number",
minlength: "Please check your GST number.",
maxlength: "Please check your GST number.",
pattern: "You have entered an invalid GST number.",
},

Related

How can I create a credit card validator using Luhn's algorithm?

I am trying to create a simple credit card validator using Luhn's algorithm. If the check digit matches the last inputted number, then it should alert the user that it is valid. Else, say that it isn't valid. Currently, I am getting an error with my sum (total) coming up as NaN. I assume that is the only problem with the code.
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "212121212121212";
let multipliedNumber;
let multipliedString;
if (number.length != 16) {
alert("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length - 1; count++) {
multipliedNumber = number[count] * multiplier[count];
console.log(multipliedNumber);
if (multipliedNumber > 9) {
multipliedNumber = multipliedNumber[0] + multipliedNumber[1];
multipliedString = multipliedString + multipliedNumber;
} else {
multipliedString = multipliedString + multipliedNumber;
}
}
console.log(multipliedString);
let checkDigit = 10 - (multipliedString % 10);
if (checkDigit == number[15]) {
alert(`${number} is a valid Credit Card number.`);
} else {
alert(`${number} is not a valid Credit Card number.`);
}
}
}
There are several issues:
multipliedNumber is a product, so it is a number type. Therefore accessing properties like [0] or [1] on it, will just evaluate to undefined. Either turn that value to string first, or (better) use arithmetic to extract the two digits:
multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
multipliedString is not initialised, so adding things to it will not give the desired outcome. Secondly, you define it as a string, but it should be a number, as with Luhn's algorithm you are supposed to sum up the resulting digits, not concatenate them. So initialise a variable like this:
sum = 0;
... and use it like you did -- although you could benefit from the += operator, and since the operation is the same for both cases, you can do it outside of the if..else blocks.
The calculation of the check digit is wrong when the modulo operation evaluates to 0: 10 - (multipliedString % 10) then returns 10, but in that case the check digit is supposed to be 0. It is much easier to just treat that last digit also in the loop and then check that you have reached a multiple of 10. This is also how the algorithm is explained on Wikipedia
Corrected version:
function checkNumber() {
let number = document.getElementById("creditCard").value;
let multiplier = "2121212121212121"; // One more character added...
let multipliedNumber;
let sum = 0 // Initialise it as a number.
if (number.length != 16) {
console.log("Please enter a Credit Card number that is 16 digits in length.");
} else {
for (count = 0; count < number.length; count++) { // Include last digit in loop
multipliedNumber = number[count] * multiplier[count];
if (multipliedNumber > 9) {
// Use arithmetic to add the two digits
multipliedNumber = multipliedNumber % 10 + Math.floor(multipliedNumber/10);
}
sum += multipliedNumber;
}
let check = sum % 10; // Simpler now because all digits were processed
if (check == 0) { // Sum is multiple of 10
console.log(`${number} is a valid Credit Card number.`);
} else {
console.log(`${number} is not a valid Credit Card number.`);
}
}
}
<input type="number" id="creditCard" placeholder="0000 0000 0000 0000">
<input type="submit" id="checkButton" value="CHECK VALIDITY" onclick="checkNumber()">

Why does if statement not work and make my element disappear using display: none?

I am building a tip calculator and I couldn't make the if statement in my function work it just skips to calculating.
function calculate() {
var bill = parseInt(document.getElementById("bill").value);
var tip = parseInt(document.getElementById("tip").value) * .01;
var persons = parseInt(document.getElementById("persons").value);
if (bill == "" || tip == "") {
alert("Please enter value");
return;
};
if (persons == "" || persons <= 1) {
persons = 1;
document.getElementById("perPerson").style.display = "none";
} else {
}
let totalTipPer = (bill * tip) / persons;
let totalPer = (bill + (tip * 100)) / persons;
let totalTip = bill * tip;
let total = bill + (tip * 100);
totalTipPer = totalTipPer.toFixed(2);
totalPer = totalPer.toFixed(2);
total = total.toFixed(2);
totalTip = totalTip.toFixed(2);
document.getElementById("total-tip/person").innerHTML = totalTipPer;
document.getElementById("total-price/person").innerHTML = totalPer;
document.getElementById("total-tip").innerHTML = totalTip;
document.getElementById("total-price").innerHTML = total;
}
document.getElementById("calculate").onclick = function () {
calculate();
document.getElementById('results').style.display = 'block';
}
I expect the div encapsulating Tip Amount per person and total per person and to not appear when the input value of persons is empty.
Function parseInt returns 'An integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.'
if you rpovide an empty value ('') it will return
NaN which is not equal to anything, even itself.
there are several ways to fix this:
check if it is a NaN with Number.isNaN(var)
use an intermediate value like var personsValue and check if it is equal to empty string ''.
use Hybrid suggested solution and assign a 0
value for falsy value('', undefined, n
ull etc...)
The issue is that persons becomes NaN, since if the value is left blank, "" becomes NaN when it is run through parseInt().
The way to fix this is by defaulting it to 0 if the field is left blank.
var persons = parseInt(document.getElementById("persons").value || 0);
as others pointed out parseInt is returning NaN if the field is blank, but this will also happen if the user inputs $5.00 for example.
Here's one way to make sure the value can be converted to a number before doing so.
// This function determines if a JavaScript String can be converted into a number
function is_numeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function calculate() {
// first put the input values into separate variables
billValue = document.getElementById("bill").value;
tipValue = document.getElementById("tip").value;
personsValue = document.getElementById("persons").value;
// use the is_numeric() function above to check if the values can be converted to numeric
if (!is_numeric(billValue) || !is_numeric(tipValue)) {
alert("Please enter values for bill and tip");
return;
}
// the rest of your code here
}
Hope this helps.

What is missing in my if statement to validate Credit Card function and how to return a value in the text?

Missing link to credit card validation using only JavaScript. Needs to have atleast two different digits and all digits should not be the same. I am unable to return values in the text please help thank you. Here is a link to the exercise.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Credit Card Validation</title>
<meta name="description" content="CHANGE THIS CONTENT DESCRIPTION">
</head>
<body>
<span>Credit Card Number* :</span>
<input class="inputForm" type="number" id="ccn" name="inputStealMoney"
placeholder="Enter Credit Card Number"><span class="restriction" id="CCNSpan"></span>
<button type="button" onclick="CCNSpan">Submit</button>
<br>
<p id="CCNSpan">Text</p>
<script>
function funcCall() {
validFormCCN();
}
function validFormCCN() {
var x, textC;
x = document.getElementById('ccn').value;
//If statement below is blank in the last () paranthesis. It needs to be filled with 'different numbers' to work
if (isNaN(x) && (x%2) ==0 && x.length==16 && ()) {
/*The if statement above is NaN() and x%2==0 is even and x.length is 16 digits and the blank () paranthesis where all the digits cannot be the same with atleast two different digits*/
return true;
}
else {
return false;
}
}
document.getElementById("CCNSpan").innerHTML = textC;
</script>
</body>
</html>
Consider using the following regex pattern:
(\d)(?!\1{15})\d{15}
This asserts that the credit number contains 16 digits, and that the first number does not repeat for the next 15 digits. This implies that there are at least 2 numbers which are not the same.
var str = "1111111111111111";
var patt = new RegExp("(\\d)(?!\\1{15})\\d{15}");
var res = patt.test(str);
console.log(res);
str = "1111111115111111";
res = patt.test(str);
console.log(res);
Of course, in practice, in a production e-commerce site, you would be using much more complex regular expressions. Visa, MasterCard, etc. have rules for how their credit card numbers are formed. You may visit this link for more information.
Your code looks somewhat like an attempt to implement the Luhn algorithm. Implementations for many languages including JavaScript can be easily found.
var luhn10 = function(a,b,c,d,e) {
for(d = +a[b = a.length-1], e=0; b--;)
c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;
return !(d%10)
};
However, not all credit card companies use the Luhn algorithm. This it is recommended to use a library function to validate credit card numbers, e.g. the jQuery Validation Plugin. Another common implementation is provided by Braemoor and a regex-based JS version can be found here.
function validateCcn(value) {
// Accept only spaces, digits and dashes
if ( /[^0-9 \-]+/.test( value ) ) {
return false;
}
var nCheck = 0,
nDigit = 0,
bEven = false,
n, cDigit;
value = value.replace( /\D/g, "" );
if ( value.length < 13 || value.length > 19 ) {
return false;
}
for ( n = value.length - 1; n >= 0; n-- ) {
cDigit = value.charAt( n );
nDigit = parseInt( cDigit, 10 );
if ( bEven ) {
if ( ( nDigit *= 2 ) > 9 ) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return ( nCheck % 10 ) === 0;
}
console.log(validateCcn('1234-1234-1234-1234'));
console.log(validateCcn('378282246310005'));

Javascript validation using isNaN and !==0

I'm new to javascript and I have input boxes that must not allow a zero value or non-numbers. I originaly tried to create a regular expression but I couldn't seem to get any of them to work correctly. I then came up with the following solution but it seems to only work some of the time. I think my if statements are jacked up. Any help with the code as far as making it better would be greatly appreciated.
HTML:
<input name="payrate" id="payrate"></td>
<input name="hours" id="hours" value="0" onclick="dollars()" onchange="dollars()"></td>
Javascript:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (!isNaN(rate) && !rate == 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
There is no need to check two times for isNaN. Try to simplify the conditions like this:
function dollars(){
var rate = 0;
rate= document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!isNaN(hours)){
// !isNan - not a Number
// !rate == 0 - value not equal to 0
if (rate > 0) {
//round value of payrate to 2 decimal places
var adjrate = Math.round(rate*100)/100;
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
}else{
alert("You entered an invalid rate.\n"+
"Please enter your hourly pay.\n"+
"Example: 8.87 value entered: " + rate);
rate = "";
disableRadio();
resetForm();
}
}else{
alert("You entered invalid or empty hours.\n"+
"Please enter the number of hours worked.\n"+ hours);
hours = "";
disableRadio();
resetForm();
}
}
You can use <input type="number" min="0.01" step="0.01" value="0.01"> element. See doc. So you will be sure that value rate and hours will be an integer.
As example - you should be able to add whatever you need in this I have commented out some of the additional function calls that were not included - but you should be able to go from here.
<input name="payrate" id="payrate">
<input name="hours" id="hours" value="0" onclick="dollar()" onkeyup="dollar()">
<script>
function dollar(){
var rate = document.getElementById("payrate").value;
var hours= document.getElementById("hours").value;
if(!hours || isNaN(hours)){
alert('hours must be a numeric value greater than zeo');
// disableRadio();
// resetForm();
return false;
}
if (!rate || isNaN(rate)) {
alert('rate must be a numeric value greater than zeo');
//disableRadio();
//resetForm();
return false;
}
var adjrate = Math.round(rate*100)/100;
/**
* commented out for example since not included in example code -
document.getElementById("payrate").value="";
document.getElementById("payrate").value= adjrate;
for (i=0; i<6; i++){
document.paycheck['tax'+i].disabled = false;
}
*/
}
</script>

wrong error message output in function

I am trying to validate a Poperty value and down payment. The conditions are as follows:
property value:
Must be present
Must be numeric - positive - whole number
Must be at least 65,000 dollars more that the down payment.
down payment:
Must be present
Must be numeric - positive - whole number
Must be at least 20% of the value of the property (propValue)
My function is (sort of) working. It doesn't pass all the validation tests. If someone can point me in the right direction as to how to improve this it would be greatly appreciated. My 2 functions for the down pay and value:
function propValueValidation(errMessages){
var propValueLength = document.mortgage.propValue.value.length;
var propValueNumber = isNaN(document.mortgage.propValue.value);
var propValue = document.mortgage.propValue.value;
var downPayPlus = document.mortgage.downPay.value + 65000;
if (!propValueLength) {
errMessages += " Property Value is a required field";
return errMessages;
}
else if (typeof propValue === 'number') {
var remainder = (propValue % 1);
if(remainder != 0){
errMessages += "Property Value must be a positive whole number";
return errMessages;
}
}
else if (propValue < downPayPlus){
errMessages += "Property Value must be at least 65,000 greater than the down payment";
return errMessages;
}
return errMessages;
}
//validate down pay
function downPayValidation(errMessages){
var downPayLength = document.mortgage.downPay.value.length;
var downPay = document.mortgage.downPay.value;
var propValueMin = document.mortgage.propValue.value * 0.2;
if (!downPayLength) {
errMessages += "Down Payment is a required field";
return errMessages;
}
else if (typeof downPay === 'number') {
var remainder = (downPay % 1);
if(remainder != 0){
errMessages += "Down Payment must be a positive whole number";
return errMessages;
}
}
else if (downPay < propValueMin){
errMessages +="Down Payment must be at least 20% of the property value";
return errMessages;
}
return errMessages;
}
HTML:
<label class="label">Property Value </label>
<input type="text" name="propValue" id="propValue" size="7" maxlength="6" >
<br>
<label class="label">Down Payment </label>
<input type="text" name="downPay" id="downPay" size="7" maxlength="6" >
when downpay is "1nn1" it will still submit the form for example. Thanks!
you can use parseInt() to confirm its a number.
var tempVal = document.mortgage.propValue.value;
var propValue = parseInt(tempVal); // this will try to extract an integer from tempVal
if (tempVal != propValue.toString()) // if true, there were non-number chars or value is NaN
{
errMessages += "Bad value, please enter an integer";
}
You should not use isNaN on string values (which input values are). Instead first convert such a string to number with Number() (or parseFloat, but Number will require the whole of the input to parse as number, while parseFloat or parseInt will accept strings that start with a number). Then call isNaN on that.
There is also a problem with the if else logic, because you have one branch for numeric data (where it will never get, because the value property of input elements is always a string), and an else on that to compare the amount with another amount. Yet for that last test the value must be numeric. So that test is in the wrong place.
Here is your first function's code with some alterations made:
function propValueValidation(errMessages){
var propValue = document.mortgage.propValue.value;
var propValueNumber = Number(propValue);
var downPayPlus = propValueNumber + 65000;
var genericMsg = ' property value was provided. Please provide a positive' +
' whole number, at least 65,000 greater than the down payment.\n';
if (!propValue.length) {
errMessages += 'No' + genericMsg;
} else if (isNaN(propValueNumber)) {
errMessages += 'A non-numerical' + genericMsg;
} else if (propValueNumber % 1) {
errMessages += 'A fractional' + genericMsg;
} else if (propValueNumber < downPayPlus){
errMessages += 'A too small' + genericMsg;
}
return errMessages;
}

Categories

Resources