check if user inserted value higher then 0 with vanilla js - javascript

I am creating a custom js validator from scratch, without the use of any libraries.
I want to validate a numeric input by checking if the user-inserted content in the input tag is great than 0:
<label>Price
<input type="text" id="price" name="price">
</label>
Attempt:
function price()
{
if (#price.value>0)
console.log('0.');
else
console.log('Incorrect');
}

Would this not work:
if(price.value.match(/^[0-9]+$/) && +(price.value) > 0){
im not quite sure what the hash symbol is being used for so i removed it in my example. Unless you are trying to find the ID in which you would have to look for the element like so:
var price = document.querySelector("#price");

function price()
{
var price = document.getElementById("#price"); // get the element
if (isNaN(price.value) || price.value <= 0) // if the value is not a number or is less than 0
console.log('Incorect');
else // otherwise
console.log('Correct');
}

How about some thing like that
var price = document.getElementById("price").value;
if (parseInt(price) > 0 && !isNaN(price)))
{
// then do something
}
else
{
// else do something
}

Related

Add another condition to Show/Hide Divs

I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

How to add a validation error message next to a field using jQuery

Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Categories

Resources