Error prompts if data entered correctly - javascript

Creating a script to prompt alert if all number entered are zeros. Script is working correctly but through JS error in firebug console if number entered correctly.
How could i solve this without error prompt.
Code -
jQuery("#EventPhone").focusout(function(){
var $this = jQuery(this);
var phoneNum = ($this.val()).toString();
var count1 = phoneNum.match(/0/g).length || "";
var phoneNumLen = phoneNum.length
if( phoneNumLen == count1 )
{
alert('All numbers in a phone number cannot be zero!!');
$this.val("");
}
});
Fiddle - http://jsfiddle.net/8XmpG/

UPDATE (if characters are allowed)
use this code - DEMO
jQuery("#EventPhone").focusout(function(){
var phoneNum = parseInt($(this).val().trim().replace( /\D+/g,''));
if(phoneNum === 0 )
alert("All numbers in a phone number cannot be zero!");
});
if characters are not allowed, use this code- DEMO
jQuery("#EventPhone").focusout(function(){
var $this = jQuery(this);
var phoneNum = $this.val().trim();
var phoneNumber = parseInt(phoneNum);
if(phoneNum == phoneNumber && phoneNumber !== 0 ) // don't use phoneNum === phoneNumber
{
alert("Right Number");
}
else{
alert('Wrong Number');
$this.val("");
}
});

Now, you have error in this line:
var count1 = phoneNum.match(/0/g).length || "";
because phoneNum.match(/0/g) could be null, so, if you check it first like this:
var count1 = (phoneNum.match(/0/g) && phoneNum.match(/0/g).length) || "";
everything will be ok.
Check for space:
var phoneNum = ($this.val()).toString().replace(' ', '');

Related

How to check if number and has nine characters?

how do I check if a text entered is a number and has nine characters in javascript?
Intengo do with the code below but shows me correctly.
function numberValidate(idtelf){
var number = document.getElementById('idtelf');
var charactersLength = number.value.length;
if(isNaN(number) || charactersLength !=9 )
{
alert( "Enter a valid number ");
}
else {
alert( "correct");
}
};
This one checks also if it's a number. Other answers would accept "123456 " (3 spaces at the end) as well.
function numberValidate(idtelf){
var input = document.getElementById('idtelf');
var number = parseFloat(input.value);
var charactersLength = input.value.length;
var numberLength = (""+number).length;
if(isNaN(number) || charactersLength !=9 || numberLength !=9 )
{
alert( "Enter a valid number ");
}
else {
alert( "correct");
}
};
If number can'n be float then instead of parseFloat() use parseInt()
You can use
HTML
<input id="idtelf">
Javscript
var number1 = document.getElementById('idtelf');
number1.onblur = function () {
var charactersLength = number1.value.replace(/\s/gi,"").length;
if(isNaN(number1.value) || charactersLength != 9)
{
alert("Enter a valid number ...");
}
else {
alert("correct");
}
};
https://jsfiddle.net/rreyaovy/5/
Try this..This handles all type of input..
function numberValidate(idtelf){
var input = document.getElementById('idtelf');
var number = input.value.toString();
var myString = number.replace(/\D/g,'');
if(number.length ==9 && number.length == myString.length)
{
alert( "Correct");
}
else {
alert( "Enter a valid number");
}
};
Demo
Here's a function that uses a simple regular expression to test if the value is a 9-digit number.
function numberValidate(id){
var number = document.getElementById(id).value,
regex = /^[0-9]{9}$/;
if (regex.test(number)) {
return true;
} else {
return false;
}
};
We can use this function like this:
function numberValidate(id){
var number = document.getElementById(id).value,
regex = /^[0-9]{9}$/;
if (regex.test(number)) {
return true;
alert();
} else {
return false;
}
};
var result1 = numberValidate('testNum1');
var result2 = numberValidate('testNum2');
var result3 = numberValidate('testNum3');
document.getElementById('result').innerHTML = 'Input 1: ' + result1 + '<br/>Input 2: ' + result2 + '<br/>Input 3: ' + result3;
<input id="testNum1" value="1234">
<input id="testNum2" value="123456789">
<input id="testNum3" value="1234567891011">
<div id="result"></div>
try like this
if(isNaN(number.value) || charactersLength !=9 )
instead of this
if(isNaN(number) || charactersLength !=9 )

Check if <form> text element is null

I wanted to do an error check in Javascript which would pop up if a form-text element is empty.
var itemPrice = parseFloat(document.getElementById("tPrice").value);
if(itemPrice < 0 || itemPrice == null)
{
alert("Please enter a valid price");
return false;
}
I have tried itemPrice == "null"and itemPrice === "null".
Any insight would be great, thank you!
To check if the value is empty, just write getElementById("tPrice").value==='' without parseFloat.
var itemPrice = parseFloat(document.getElementById("tPrice").value);
if(getElementById("tPrice").value==='' || itemPrice < 0)
{
alert("Please enter a valid price");
return false;
}
This will give you the results you are looking for
if (typeof itemPrice == "undefined" || itemPrice <= 0) { ... }
You can use the isNaN function to tell if the function is not a number, which not only works for blank / empty values but also for any random text.
In the example below stackoverflow does not allow alert statements to be run, so I changed it to display the results inline.
function validateField() {
var itemPrice = parseFloat(document.getElementById("tPrice").value),
result = document.getElementById("result");
if(isNaN(itemPrice) || itemPrice < 0) {
result.innerHTML = '<span style="background:red;color:#fff">Please enter a valid price</span>';
return false;
}
result.innerHTML = '<span style="background:green;color:#fff">Price is valid</span>';
return true;
}
<input type="text" id="tPrice" />
<button onclick="validateField();">Validate Field</button>
Result:<span id="result"></span>
If the itemPrice have to be a number > 0 try this:
var itemPrice = document.getElementById("tPrice").value;
if(!(itemPrice > 0)) {
alert("Please enter a valid price");
return false;
}

What is the right way to check a input form field value(empty and null..) using jQuery?

I have some input filed into a form. I am trying to check the empty and null of those value.
My js code as:
$(function(){
$('#submit').click(function(){
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
var path = '/admin/exam_schedule';
if (cid ==''||cid==null || sid==''||cid==null || d==''||d==null || t==''||t==null) {
alert('Input all data fields');
}
else{
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});
});
But the problem of this code are: When I give space into the input field then it takes the space as input.But, I want to validate all of the possible way, so that I can take real data as input.
val() will only return null for a select element, everything else should return '', therefore, if you aren't using a select element then str != '' or str.length > 0 should be sufficient.
If you are using a select element then you check whethre the value is assigned first e.g. str && str != '' or str && str.length > 0 (or alternatively you default null to '' for consistency).
If you want to exclude whitespace-only strings then use trim() during validation.
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
if (cid.trim() == '' || sid.trim() == '' || d.trim() == '' || t.trim() == '') {
// data invalid
}
else {
// data valid
}
Try,
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
DEMO
Improvised version,
var condition = false;
$('#CTID,#sbj,#bdate,#time').each(function(){
if($.trim(this.value) === "") {
condition = true;
return false;
}
})
if(condition){ alert('Input all data fields'); }
Full code would be,
$('#submit').click(function(e){
e.preventDefalut();
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
else {
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});

javascript If Variable(s) is True

I'm not sure if I'm misunderstanding how True/False works in Javascript or not.
In my Jquery script below I'm declaring 6 variables as false.
If the regex validation conditions are good, then I redeclare the variable(s) to true.
On the bottom is a simple alert() to tell me when all variables are true.
The validation conditions are working (removing/adding classes), but the alert does not show up. That's why I'm not sure if I'm messing up the true/false part or not.
$('#password1').keyup(function() {
var checkLength = false;
var checkLetter = false;
var checkCaps = false;
var checkNum = false;
var checkSymbol = false;
var checkSpace = false;
var pswd = $(this).val();
//validate the length
if(pswd.length < 6 ){
$('#length').removeClass('valid').addClass('invalid');
}else{
$('#length').removeClass('invalid').addClass('valid');
checkLength = true;
}
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
}else{
$('#letter').removeClass('valid').addClass('invalid');
checkLetter = true;
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
}else{
$('#capital').removeClass('valid').addClass('invalid');
checkCaps = true;
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
}else{
$('#symbol').removeClass('valid').addClass('invalid');
checkSymbol = true;
}
//validate no spaces
if(pswd.match(/\s/)){
$('#spaces').removeClass('valid').addClass('invalid');
}else{
$('#spaces').removeClass('invalid').addClass('valid');
checkSpace = true;
}
// here is where I'm concerned I'm wrong
if(checkLength == true && checkLetter == true && checkCaps == true && checkNum == true && checkSymbol == true && checkSpace == true){
alert("All good");
}
});
Would someone double check me?
At first, there is no need to write checkLength == true, checkLength is enough since they are all boolean variables.
Second, in some of your conditions you assign class invalid but set the var to true, while in others you do it vice versa. Every check... = true should be in the same branch with class = valid.
Also, personally, I would adapt the validity conditions, to have all positive events either in the if or in the else branch, but not mixed like you do at the moment.
Lastly, I always try to avoid duplicate code. There are a lot of places you could refactor, but you could start easy with setting the classes in a separate function.
See it working in this fiddle.
$('#password1').keyup(function() {
var checkLength = false;
var checkLetter = false;
var checkCaps = false;
var checkNum = false;
var checkSymbol = false;
var checkSpace = false;
var pswd = $(this).val();
//validate the length
// reverse the condition, to have the valid state in the if branch as well
if(pswd.length >= 6 ){
setValid('#length');
checkLength = true;
}else{
setInvalid('#length');
}
//validate letter
if(pswd.match(/[A-Za-z]/)){
setValid('#letter');
checkLetter = true;
}else{
setInvalid('#letter');
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
setValid('#capital');
checkCaps = true;
}else{
setInvalid('#capital');
}
//validate number
if(pswd.match(/\d/)){
setValid('#number');
checkNum = true;
}else{
setInvalid('#number');
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
setValid('#symbol');
checkSymbol = true;
}else{
setInvalid('#symbol');
}
//validate no spaces
if(!pswd.match(/\s/)){
setValid('#spaces');
checkSpace = true;
}else{
setInvalid('#spaces');
}
function setValid(e){$(e).removeClass('invalid').addClass('valid')}
function setInvalid(e){$(e).removeClass('valid').addClass('invalid')}
if(checkLength && checkLetter && checkCaps && checkNum && checkSymbol && checkSpace){
alert("All good");
}
console.log("keyup");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password1" type="text">
All of these have check* = true in the wrong place:
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
}else{
$('#letter').removeClass('valid').addClass('invalid');
checkLetter = true;
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
}else{
$('#capital').removeClass('valid').addClass('invalid');
checkCaps = true;
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
}else{
$('#symbol').removeClass('valid').addClass('invalid');
checkSymbol = true;
}
Insert the statements in the block following the if (where they are deemed valid) as opposed to in the else (where they are deemed invalid):
//validate letter
if(pswd.match(/[A-Za-z]/)){
$('#letter').removeClass('invalid').addClass('valid');
checkLetter = true;
}else{
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if(pswd.match(/[A-Z]/)){
$('#capital').removeClass('invalid').addClass('valid');
checkCaps = true;
}else{
$('#capital').removeClass('valid').addClass('invalid');
}
//validate number
if(pswd.match(/\d/)){
$('#number').removeClass('invalid').addClass('valid');
}else{
$('#number').removeClass('valid').addClass('invalid');
checkNum = true;
}
//validate symbols
if(pswd.match(/[^a-zA-Z0-9]/)){
$('#symbol').removeClass('invalid').addClass('valid');
checkSymbol = true;
}else{
$('#symbol').removeClass('valid').addClass('invalid');
}
And, although there are better ways of writing validation, this is a similar, yet more concise version of your snippet:
$("#password1").keyup(function() {
var pswd = $(this).val();
var checkLength = pswd.length >= 6;
var checkLetter = /[A-Za-z]/.test(pswd);
var checkCaps = /[A-Z]/.test(pswd);
var checkNum = /\d/.test(pswd);
var checkSymbol = /[^A-Za-z0-9]/.test(pswd);
var checkSpace = !/\s/.test(pswd);
$("#length") .removeClass("valid invalid").addClass(checkLength ? "valid" : "invalid");
$("#letter") .removeClass("valid invalid").addClass(checkLetter ? "valid" : "invalid");
$("#capital").removeClass("valid invalid").addClass(checkCaps ? "valid" : "invalid");
$("#number") .removeClass("valid invalid").addClass(checkNum ? "valid" : "invalid");
$("#symbol") .removeClass("valid invalid").addClass(checkSymbol ? "valid" : "invalid");
$("#spaces") .removeClass("valid invalid").addClass(checkSpace ? "valid" : "invalid");
if(checkLength && checkLetter && checkCaps && checkNum && checkSymbol && checkSpace) {
alert("All good");
}
});
To me, it seems that your assignments are valid statements. Whether or not they are getting set the way you want is a different matter.
It is most likely that one of the flags is not being set the way you want it to be set. To check this, you could alert each of your flags (checkCaps, etc) to confirm that each value is set the way you want. If all of the true/false is correct, then the issue would be in your final if statement.
As many people have suggested, removing the == true is a good idea. Since Javascript is dynamically typed, there is a slight possibility that it is not treating your flags as a boolean, but as something else.
If removing the == true does not work, you could check different pairs of flags to see which one makes the entire statement false.

JavaScript Form onkeyup Validation Errors

Not getting any errors in Aptana, so something I'm doing probably doesn't make sense. Basically, I am getting the value from a form and checking it against a regex. If the new checked variable isn't empty then I output to a different div that it is valid, and that it is not valid if the variable is empty.
<script type="text/javascript">
var age_regex=/(1[8-9]|2[0-9]|3[0-5])/;
var error_box= document.getElementById('error_box');
function checkAge(x){
var age = document.getElementById(x).value;
var checked_age = test.age_regex(age);
if (checked_age.value != "")
error_box.innerHTML = "Correct!";
else {
error_box.innerHTML = "Incorrect!";
}
}
</script>
Why regex for age ? How about this :
function checkAge(str) {
if(parseInt(str, 10) != str) {
return false;
}
if(parseInt(str, 10) < 18 || parseInt(str, 10) > 35)
{
return false;
}
}

Categories