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;
}
Related
I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});
so I have been learning basic JS and i can't get form validation to work for numbers. I will post a code snippet below. Please I am a noob so can I possibly have an answer that is easier to understand from someone who is just learning the language. The first three if statements work fine, but the fourth I have trouble with...
var checkbox = function() {
var error = "";
var firstname = document.getElementById("fn").value;
var lastname = document.getElementById("ln").value;
var email = document.getElementById("Email").value;
var age = parseInt(document.getElementById("age").value);
var address = document.getElementById("A").value;
var phone = parseInt(document.getElementById("pn").value);
if(firstname.length < 1){
error = "Enter a valid first name!";
}
if(lastname.length < 1){
error += "\nEnter a valid last name!";
}
if(email.length <1){
error += "\nEnter a valid email!";
}
if(age.length < 1 ){
error += "\nEnter a valid age!";
}
if(error.length){
alert(error)
return false;
}
return true;
}
you can try with this one
if(firstname.trim() == ""){
error = "Enter a valid first name!";
}
if(lastname.trim()==""){
error += "\nEnter a valid last name!";
}
if(email.trim() ==""){
error += "\nEnter a valid email!";
}
if(age.trim() == "" ){
error += "\nEnter a valid age!";
}
if(error.length>0){
alert(error)
return false;
}
What are you checking your age field against on? Are you checking for its presence? if so, you can do this:
if(!age) {
error += "\nThis field is required";
}
If you are checking if the value in the age field is a number, you can do this:
if(typeof age !== "number") {
error += "\nPlease enter a valid number!";
}
If you are checking if the age field is under a certain age range you can do this:
if(age !== 30) {
error += "\nYou are under 30!";
}
You should check the length of document.getElementById("age").value before call parseInt. Otherwise variable age can be NaN. For example:
var ageVal = document.getElementById("age").value;
var age;
if (ageVal){ //same as ageVal.length > 0
age = parseInt(age);
if (!age){// it can be NaN
error += "\nEnter a valid age!";
}
}
else
{
error += "\nEnter an age!"; //here we have age not set
}
Please try this
if(isNaN(age)){
error += "\nEnter a valid age!";
}
isNan() is an inbuilt javascript function. More information can be found at http://www.w3schools.com/jsref/jsref_isnan.asp
I have written some javascript code in which i have made a recursive function. I am expecting a numeric value however i recieve an NaN. How can i solve this?
<script language="javascript">
function toperform()
{
var proceed=confirm("Do you want to proceed?");
if (proceed==true)
{
var a = checknum("num1");
var b = checknum("num2");
alert("The sum is "+(a+b));
}
else
{
alert("You chose not to proceed!");
}
}
function checknum(arg)
{
var num=parseInt(prompt("Enter "+arg));
if (isNaN(num))
{
alert("Please enter a valid number");
num=checknum(arg);
}
return num;
}
</script>
I think this is more semantic, repeat until get a valid number, but not recursively
function checknum(arg)
{
var num = null ;
while (isNaN(num))
{
if (num != null)
alert("Please enter a valid number");
var input = prompt("Enter "+arg);
num = parseInt(input);
}
return num;
}
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;
}
}
pl. advise me how do i validate the array values in javascript.
i am posting the code that i am currently using. the problem is that even after filling up all the values, i still keep getting the validation error message.
pl. advise me where am i wrong
function chkdate() {
var x = document.forms["main"]["date"].value;
if (x == null || x == "") {
document.forms["main"]["date"].focus();
document.forms["main"]["date"].style.background = 'red';
alert("Date Cannot be empty");
return false;
}
}
function chkempty() {
var len = document.forms["main"]["item[]"].length;
if (len == undefined) {
var ic = document.forms["main"]["item[]"].value;
var iq = document.forms["main"]["qty[]"].value;
var ip = document.forms["main"]["price[]"].value;
if (ic == null || ic == "") {
document.forms["main"]["item[]"].focus();
document.forms["main"]["item[]"].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iq == null || iq == "") {
document.forms["main"]["qty[]"].focus();
document.forms["main"]["qty[]"].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ip == null || ip == "") {
document.forms["main"]["price[]"].focus();
document.forms["main"]["price[]"].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
} else for (i = 0; i < len; i++) {
var ica = document.forms["main"]["item[]"][i].value;
var iqa = document.forms["main"]["qty[]"][i].value;
var ipa = document.forms["main"]["price[]"][i].value;
if (ica == null || ica == "") {
document.forms["main"]["item[]"][i].focus();
document.forms["main"]["item[]"][i].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iqa == null || iqa == "") {
document.forms["main"]["qty[]"][i].focus();
document.forms["main"]["qty[]"][i].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ipa == null || ipa == "") {
document.forms["main"]["price[]"][i].focus();
document.forms["main"]["price[]"][i].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
}
}
other details are:-
form name: main
the input boxes item,qty and price are dynamic rows based on user's requirement.
thanks all.
I suggest you as first point to use JQuery in conjunction with validate plugin.
Then for your case follow this example that works fine for me:
$("#testform").validate({
rules: {'qty[]': {required: true,minlength: 1},
//other rules here
},
messages: {
'qty[]': "Select at least one qty",
//other custom error msgs go here
}
});
<input name="qty[]" id="1" value="1" type="checkbox" />
<input name="qty[]" id="2" value="2" type="checkbox" />
<input name="qty[]" id="3" value="3" type="checkbox" />
N.B. that the name of the field of array values must be specified with quotes ('qty[]')
or else you'll get a js error.