html - Number validation in JavaScript -
i have created external javascript validate form created in html. of validation works, when use same code validate other fields not work. e.g. postcode must contain numbers - if not, postcode invalid.
i tried using same code credit card, i.e. credit card must have 16 digits - if not, credit card number invalid. wrote code postcode , worked, when tried reaarrange suit credit card function, did not work. not sure why? should have used different function?
here external javascript:
function validateform() { if (isnan(document.getelementbyid("postcode").value)) { alert ("your postcode not valid"); } else { alert ("you have entered postcode correctly"); } if (document.getelementbyid ("email").value.length < 5 || document.getelementbyid ("email").value.indexof("@")== -1) { alert("please enter email min 5 chars , include @ symbol"); document.getelementbyid("email").focus(); return false; } if (isnan(document.getelementbyid("creditcard").value)) { alert ("your creditcard not valid"); } else { alert ("you have entered creditcard correctly"); } alert("thank submission!"); return true; }
so first off, don't want prompt user 10 error dialogs @ time. should nest if else
clauses & function stop after first error. second, isnan
doubtfully evaluator because input.value
may return value of type string. using regex more robust way of error checking inputs. third, want account user's confusion mistakes. users think (me too): 'wait, should write dash on credit card here?'.
so you'll remove dots, dashes & whitespace before proceeding (those unknowingly included). other chars invalid. credit card input, be:
var ccval = document.getelementbyid("creditcard").value; // remove dots, dashes & whitespace ccval = ccval.replace(/(\s|\.|\-)/g, ''); // if other chars there, input value = incorrect & stop function if ( ccval.match(/\d/) ) { alert('a credit card number has decimals, silly.'); return false; } else { // check length if ( ccval.length !== 16) { alert('a credit card has 16 decimals, silly.'); return false; } else { // more checks document.getelementbyid('myform').submit() } }
see implementation example here: http://jsbin.com/betawahi/1/edit
Comments
Post a Comment