check if input text field contains min val on submit - javascript

I have a pretty simple HTML web form...
I am taking the data and serializing to JSON (and will eventually send somewhere else. But, for now am using console.log for test).
When the user fills out the form, and then clicks submit; I would like to simply check the value of my input text field, and make sure the user has at-least entered a number higher then 0, but not 0.
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
I would like this validation to run before, my serialize function below it fires. Essentially, I want to check or validate this before data is sent. If the user enters 0, I don't want to send.
Below is my full JavaScript. (I still cannot get validate function as described above).
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
$('form').submit(function (e) {
function validateForm(){ // would like to check before below fires for serialize
var form = document.getElementById("form"), inputs = form.getElementsByTagName("input"),
input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
// if the value is not a valid number or it's less than or equal 0
if(isNaN(input.value) || +input.value < 0) {
flag = false;
input.focus();
console.log("error!");
// break;
}
}
return(flag);
}
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
});

Simple validate number input. Try this.
$("#submit").on("click", function(){
inputValue = $("input[name='age']").val();
var num = parseInt(inputValue);
if(isNaN(num) || num <= 0){
console.log(inputValue + " Invalid number!");
} else {
console.log(inputValue + " Valid number!");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<input type="button" id="submit" value="Submit"\>

To accomplish that, I'm (more or less) usually do this:
HTML
<form action="(action url)" id="form" method="post" onsubmit="return validateForm()">
//form contents
</form>
JS
function validateForm() { // would like to check before below fires for serialize
//var form = document.getElementById("form"), inputs = form.getElementsByTagName("input"),
//If you use jQuery, it more preferred to write like this:
var form = $('#form'), inputs = form.find('input'), input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
// if the value is not a valid number or it's less than or equal 0
if(isNaN(input.value) || +input.value < 0) {
flag = false;
input.focus();
console.log("error!");
}
//do the break
if (!flag) break;
}
if (flag) {
var data = $(this).serializeFormJSON();
console.log(data);
}
return flag;
}

Related

Check if all text inputs are empty, show alert with for if/else statement?

beginner here. I'm trying to use a conditional to check whether if the text inputs have been filled out, otherwise if empty, prompt an alert but it doesn't appear to do anything? Is my JS poorly laid out? Here is my jsfiddle. https://jsfiddle.net/rtomino/4ywq9n3n/2/
Thank you!!
<div>
<label for="cand1">Candidate 1</label>
<input class="candidate" id="cand1" placeholder="Candidate">
</div>
<div>
<label for="cand2">Candidate 2</label>
<input class="candidate" id="cand2" placeholder="Candidate">
</div>
<div>
<label for="cand3">Candidate 3</label>
<input class="candidate" id="cand3" placeholder="Candidate">
</div>
The JS
function candidateNames() {
var inputs = document.getElementsByTagName("input");
var result = [];
for ( var i = 0; i < inputs.length; i += 1 ) {
result[i] = inputs[i].value;
if (inputs === '' || null || 0) {
alert('Need to fill inputs');
}
}
document.getElementById("candidateName1").innerHTML = result[0];
document.getElementById("candidateName2").innerHTML = result[1];
document.getElementById("candidateName3").innerHTML = result[2];
}
You are checking if you inputs array is empty and not if the current input's value is empty.
See my inline comments.
function candidateNames() {
var inputs = document.getElementsByTagName("input");
var result = [];
for ( var i = 0; i < inputs.length; i += 1 ) {
result[i] = inputs[i].value;
if (inputs[i].value == '') { // check if value is empty
alert('Need to fill inputs');
return; // stop the function
}
}
document.getElementById("candidateName1").innerHTML = result[0];
document.getElementById("candidateName2").innerHTML = result[1];
document.getElementById("candidateName3").innerHTML = result[2];
}
//Event listener to calculate button to call all above functions
document.getElementById("btn").addEventListener("click", calculateVotes, false);
function calculateVotes() {
candidateNames();
}
You are checking for (inputs === '' || null || 0), which is wrong as inputs is an array, you need to do something like this:
function candidateNames() {console.log('here');
var inputs = document.getElementsByTagName("input");
var result = [];
for ( var i = 0; i < inputs.length; i += 1 ) {
result[i] = inputs[i].value;
if (results[i] === '' || null || 0) {
alert('Need to fill inputs');
}
}
document.getElementById("candidateName1").innerHTML = result[0];
document.getElementById("candidateName2").innerHTML = result[1];
document.getElementById("candidateName3").innerHTML = result[2];
}

How should I improve my javascript form validation?

I grabbed the form from some random site because I'm only interested writing the javascript at the moment.
I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.
Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?
I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)
Any thoughts on this would be appreciated.
Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/
document.getElementById("newForm").addEventListener("submit", enterForm);
function enterForm(event) {
event.preventDefault();
var dropdown = document.getElementById('dropDown');
if (document.getElementById('fname').value === ''){
document.getElementById('fname').focus();
alert('Enter text.');
} else if (document.getElementById('eMail').value === ''){
document.getElementById('eMail').focus();
alert('Enter text.');
} else if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
alert('Enter text.');
} else if (!dropDown.value) {
document.getElementById('dropDown').focus();
alert('Choose an option.');
} else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
{ alert ( "Please choose a checkbox" );
return false;
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please check a radio button.");
return formValid;
return false;
};
If you use HTML5, and assuming you're NOT using jQuery for anything (just native JavaScript), a good convention would be to assign a class to all input elements in the form that you want to validate (or if they all need to be validated, you can get all child elements of the form), and use getElementsByClassName(). With HTML5 data-* attributes, you can assign something like data-invalid-error-message to set the error message for the element itself.
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
From there, you can perform a loop across all elements, check if they're empty, and then grab the data-invalid-error-message attribute and display it to the user without doing nested if statements.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
document.getElementById("newForm").addEventListener("submit", function (event) {
event.preventDefault();
if (!document.getElementById('fname').value) {
return alert('Enter text.');
}
if (document.getElementById('eMail').value === '') {
document.getElementById('eMail').focus();
return alert('Enter text.');
}
if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
return alert('Enter text.');
}
var dropdown = document.getElementById('dropDown');
if (!dropdown || !dropDown.value) {
document.getElementById('dropDown').focus();
return alert('Choose an option.');
}
if (( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false )) {
return alert("Please choose a checkbox");
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
}
i++;
}
if (!formValid) {
return alert("Please check a radio button.");
}
// Form is valid here
});
Here is some improvements. Updated Fiddle
I would like to validate form with required property, but it does not support validation of group of options and radio groups
If you're OK not supporting IE8, you can use querySelectorAll to dynamically get all the nodes of different types within your form and validate them accordingly. This will work for a form with any number of inputs:
function validateForm(formNode) {
var formValid = true;
var textFlds = formNode.querySelectorAll('input[type="text"],input[type="email"],input[type="password"],textarea');
var dropdowns = formNode.querySelectorAll('select');
var checks = formNode.querySelectorAll('input[type="checkbox"]');
var anyChecked = false;
var radios = formNode.querySelectorAll('input[type="radio"]');
var anyRadios = false;
for (var i = 0, l = textFlds.length; i < l; i++) {
if (!textFlds[i].value) {
textFlds[i].focus();
alert('Please enter text into the ' + textFlds[i].name + ' field.');
formValid = false
break;
}
};
for (var i = 0, l = dropdowns.length; i < l; i++) {
if (formValid && !dropdowns[i].value) {
dropdowns[i].focus();
alert('Please choose an option from the ' + dropdowns[i].name + ' selector.');
formValid = false
break;
}
};
for (var i = 0, l = checks.length; i < l; i++) {
if (checks[i].checked) {
anyChecked = true;
break;
}
};
if (formValid && !anyChecked) {
alert('Please choose at least one of the checkboxes.');
formValid = false;
}
for (var i = 0, l = radios.length; i < l; i++) {
if (radios[i].checked) {
anyRadios = true;
break;
}
};
if (formValid && !anyRadios) {
alert('Please check a radio button.');
formValid = false;
}
return formValid;
}
document.getElementById('newForm').addEventListener('submit', function (evt) {
evt.preventDefault();
validateForm(this);
});
This could be prettied up a bit, but you get the idea. (fiddle here)

Javascript validation - Error message only flashes for a second

I have this simple HTML project that validates an empty text and radiobutton field. The error is being displayed if one of the fields are empty, but the error message only flashes on the screen for a second, before disappearing again. Why is this happening?
Here's my HTML code
<form id="food_form">
<p>
<label>Your Name:
<input type="text" id="user_name" name="user_name">
</label>
<span id="error_user_name" class="error"></span>
</p>
<p>
Favorite Food?
<span id="error_radiobutton" class="error"></span><br>
<label><input type="radio" name="radiobutton" value="pizza">Pizza</label><br>
<label><input type="radio" name="radiobutton" value="burger">Burger</label><br>
<label><input type="radio" name="radiobutton" value="spaghetti">Spaghetti</label><br>
</p>
<input type="submit" value="Submit">
And then my Javascript code
<script>
document.getElementById("food_form").onsubmit = validateForm;
function validateForm() {
var validName = validateTextBox("user_name", "error_user_name"),
validRadiobutton = validateRadioButton();
}
function validateTextBox(fieldId, errorId) {
var text = document.getElementById(fieldId).value,
errorSpan = document.getElementById(errorId);
if (text === "") {
errorSpan.innerHTML = "* please input your name";
}
}
function validateRadioButton() {
var radiobutton = document.getElementById("food_form").radiobutton,
errorSpan = document.getElementById("error_radiobutton"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick something.";
}
}
Your response would be kindly appreciated.
Your function validateForm sets the error message but then you call validateRadioButton() which sets again errorSpan.innerHTML = "";. That is the reason of the "flash"
You are validating the form, but you need to return false if validation fails on submit event. Try this
function validateForm() {
var isTextBoxValid = validateTextBox("user_name", "error_user_name"),
isRadioButtonValid = validateRadioButton();
return isTextBoxValid || isRadioButtonValid;
}
function validateTextBox(fieldId, errorId) {
var text = document.getElementById(fieldId).value,
errorSpan = document.getElementById(errorId),
isValid = true;
if (text === "") {
errorSpan.innerHTML = "* please input your name";
isValid = false;
}
return isValid;
}
function validateRadioButton() {
var radiobutton = document.getElementById("food_form").radiobutton,
errorSpan = document.getElementById("error_radiobutton"),
isChecked = false, i,
errorSpan.innerHTML = "";
for (i = 0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick something.";
}
return isChecked;
}
In the above code we are returning Boolean value (true / false) for each of the functions and we are submitting the form if one of them is true
Try putting the submit button outside of the form element.
I've been having the same problem and this just worked for me.

input field: limit the number of letters and numbers typed

Is there a way to limit the number of letters and numbers allowed to type in to an input field? I would like to only allow 3 letters and 2 numbers to be typed in, in whatever order.
Is this possible using the jQuery Mask Plugin? Or not?
See my jsFiddle here: http://jsfiddle.net/0akoL2x2/
html:
<input type="text" class="preview" size="30" placeholder="Preview text" class="text-input" maxlength="5" autofocus />
jquery:
jQuery('.personalisation').mask("XXXZZ", {
translation: {
'X': {pattern: /[A-Za-z0-9]/},
'Z': {pattern: /[A-Za-z0-9]/},
}
How about using a data attribute? Let's call it data-temp:
<input type="text" class="alnum" maxlength="5" data-temp="">
Use $(document).on('input'... to monitor all changes (even dynamic elements), and revert back immediately if the new value exceeds the maximum. Otherwise, let it happen, and update data-temp to this new value.
$(document).on('input', '.alnum', function(){
var txt = $(this).val();
if(
txt.replace(/[^0-9]/g,"").length > 2 ||
txt.replace(/[^A-Za-z]/g,"").length > 3 ||
txt.replace(/[a-zA-Z0-9]/g,"").length != 0
){
$(this).val( $(this).data('temp') );
return;
}
$(this).data('temp', txt);
});
JSFiddle demo
Here is a fiddle that works:
http://jsfiddle.net/igorshmigor/k2ss62gg/3/
The JS code looks like this:
var numberCountLimit = 2;
var letterCountLimit = 3;
$(document).ready(function() {
$('.preview').keypress(function(key) {
if (key.charCode == 0){
return true;
}
var current = $(this).val();
var filtered = current.replace(/[^a-z0-9]/gmi,'');
$(this).val(filtered);
var digits = filtered.replace(/[^0-9]/gmi,'');
var alpha = filtered.replace(/[^a-z]/gmi,'');
var digitCount = digits.length;
var alphaCount = alpha.length;
var isNumber = false;
var isAlpha = false;
if (key.charCode > 47 && key.charCode < 58){
isNumber = true;
if (digitCount >= numberCountLimit){
return false; // too many digits
}
}
if (key.charCode > 64 && key.charCode < 123){
isAlpha = true;
if (alphaCount >= letterCountLimit){
return false; // too many letters
}
}
if (!isAlpha && !isNumber){
return false;
}
});
});
P.S.: I don't think this can be done with just the jQuery Mask Plugin.
Give your text box an ID.
$("#box").mask('XXXZZ', {'translation': {
X: {pattern: /[A-Za-z0-9]/},
Z: {pattern: /[A-Za-z0-9]/}
}
});
JSFiddle
How about this, you hook the keypress and check the number/letter counters and if it exceeds you will just ignore the keypress (by returning false)
var numberCount = 0;
var numberCountLimit = 2;
var letterCount = 0;
var letterCountLimit = 3;
$(document).ready(function() {
$('.personalisation').keypress(function(key) {
var currentText = $(this).val();
numberCount = 0;
letterCount = 0;
for (var i = 0, len = currentText.length; i < len; i++) {
if(currentText.charCodeAt(i) < 48 || currentText.charCodeAt(i) > 57) {
//Is number
if((numberCount+1) > numberCountLimit) {
return false;
}
numberCount++;
} else {
//Is letter
if((letterCount+1) > letterCountLimit) {
return false;
}
letterCount++;
}
}
return true;
});
}

Javascript onclick form validation

Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...
function ValidateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++) {
if(validChars.indexOf(val.charAt(i)) == -1)
alert('Please enter valid number');
return false;
}
return true;
}
<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >
Pay attention to the statement start and end - the "return false;" will terminate the "for" loop on the first iteration.
Correct code:
function ValidateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++) {
if(validChars.indexOf(val.charAt(i)) == -1) {
alert('Please enter valid number');
return false;
}
}
return true;
}
format your if correctly, else it will consider only first statement.
for(var i = 0; i < val.length; i++) {
if(validChars.indexOf(val.charAt(i)) == -1)
{
alert('Please enter valid number');
return false;
}
}
Use regular expressions!
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
var regex = /^[0-9\.]+$/;
if(regex.test(value))
return true
else {
alert("Please enter a valid number");
return false;
}
}
However, that regex allows 1.22.3.6...2 as an input, which is probably not desired. You probably want to have the regex ^(\d+(\.\d+)?|\.\d+)$
Also, HTML tags should be lower case, and attributes should be quoted:
<input type="number" id="tbNumber" />
<input type="submit" name="action" value="Save Changes" onclick="return validateNumeric();" />

Categories

Resources