How to check value length with using Javascript? - javascript

Hello everyone I would like to ask how to check value's length from textbox ?
Here is my code :
#*<script>
function validateForm() {
var x = document.forms["frm"]["txtCardNumber"].value;
if (x == null || x == "" ) {
alert("First name must be filled out");
return false;
}
}
</script>*#
When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.

You could use x.length to get the length of the string:
if (x.length < 5) {
alert('please enter at least 5 characters');
return false;
}
Also I would recommend you using the document.getElementById method instead of document.forms["frm"]["txtCardNumber"].
So if you have an input field:
<input type="text" id="txtCardNumber" name="txtCardNumber" />
you could retrieve its value from the id:
var x = document.getElementById['txtCardNumber'].value;

Still more better script would be:
<input type="text" name="txtCardNumber" id="txtCardNumber" />
And in the script:
if (document.getElementById(txtCardNumber).value.length < 5) {
alert('please enter at least 5 characters');
return false;
}

Related

Most efficient way to verify multiple html table row inputs in a JS cycle?

Very much appreciated if you can help me since I am a newbie on this.
I have a huge html table with more than 10 columns and around 20 rows.
I want to do a javascript cycle to verify the inputs of all the rows. My strategy was to insert Ids in each in which each row's id always increases +1. For example:
<td><input id="ingredient_percentage_1" type="text" name=" " form="form1" />%</td>
<td><input id="ingredient_percentage_2" type="text" name=" " form="form2" />%</td>
The code I've done is like this:
function verifyPercentages(){
var total = 0;
var i;
if (batch.value === "") {
alert ("Please insert value in Batch Size field");
return false;
}
else {
for (i=1; i<19; i++){
var percentage = document.getElementById('ingredient_percentage_'+i);
if( (((i>1) && (i<5)) || (i==11) || (i==13)) && (percentage.value == "")) {
alert ("Mandatory fields are not filled up");
return false;
}
if ((i>6) && (i<9) && (percentage.value == "")) {
alert ("Please select an option in the Product type field above");
return false;
}
if ((i>8) && (i<11) && (percentage.value >= 1)) {
alert ("Please make sure that the percentages for oil are less than 1%");
return false;
}
if ((i>14) && (i<17) && (percentage.value >= 1)) {
alert ("Please make sure that (...)");
return false;
}
if (percentage == null) continue;
}
calculatePercentages();
}
}
But I feel that is not very optimized. Is there a more efficient/clean way to do this?
Many thanks
Not wanting to interfere with your tech choices, but you could do this very easily (and robust!) with built in html5 validation. It will work on all modern browsers. You can do more this way than you probably believe. One example of how an email input field in a form could be validated:
<input
id="useremail"
type="text"
placeholder="your.email#example.com"
required
minlength="6"
maxlength="90"
pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$"
title="Wrong email address format">
Result when error is thrown on Chrome/Brave/Chromium:
A more precise error text above, albeit onerous, would be "The email must contain between 5 and 89 alphanumeric characters plus the '#'".
In order to run your function when the form fully validates you can add it into your submit event like so:
const submitButton = document.querySelector('.btn-submit')
submitButton.addEventListener('click', (e) => {
e.preventDefault()
calculatePercentages()
})
One alternative is to use Javascript's querySelectorAll with enumeration. Also, many other approaches. In the example below I provide alternative ways to iterate over the HTML elements. I comment where the respected logic should go
The bottom example uses the querySelectorAll to match partially matching id string name values.
The below selector example means to locate an element where the attribute id that does begin with the string "ingredient_".
Implementations Documentation
Document Query Selector All
Document Query Selector
Note
^ matches the start
* matches any position
$ matches the end
Edits: Comparison element.value == "" may cause unexpected type coercion. That is why you may notice the if statement logic changed a little from your initial code provided.
function verify() {
elements = document.querySelectorAll(`[id ^= "ingredient_`);
Array.prototype.forEach.call(elements, callback);
function callback(element, i) {
if ((((i > 1) && (i < 5)) || (i === 11) || (i === 13)) && (element.value === "")) {
// Logic
}
if ((i > 6) && (i < 9) && (element.value === "")) {
// Logic
}
if ((i > 8) && (i < 11) && (element.value >= 1)) {
// Logic
}
if ((i > 14) && (i < 17) && (element.value >= 1)) {
// Logic
}
// Debug
console.log('i:', i, 'id:', element.id, 'value:', element.value)
}
}
verify();
<td><input id="ingredient_percentage_1" type="text" name=" " value="1" form="form1" />%</td>
<td><input id="ingredient_percentage_2" type="text" name=" " value="2" form="form2" />%</td>

Customize alert/error message based on the selector which is not selected

I have three selectors and currently if anyone of them is not selected, the alert message is "Please fill in the fields".
However, I want to customize the alert.
Suppose out of 3 only 1 selector is not selected - say "dimension" than how can I amend the alert to " Please fill in the field - Two".
My current code is:
if (
checkforNullEmptySelect("group")
&& checkforNullEmptySelect("one")
&& checkforNullEmptySelect("two")
&& checkforNullEmptySelect("three")
) {
// alert("Values filled in correctly");
formValid = true
getData();
return true;
} else {
alert(alertMessageArr.correctFields);
return false;
}
I am assuming your HTML structure to be as given below:
<input id="one" type="text"/>
<input id="two" type="text"/>
<input id="three" type="text"/>
Snippet to check fields are empty or not:
if(inputOne === 0 && inputTwo === 0 && inputThree === 0){
alert("Please fill all fields");
}else{
$('input').each(function() {
if ($(this).val() != '') { //Or $(this).length > 0
alert('all inputs filled');
}
else{
alert('theres an empty input'); //alert selectors if needed
return false
}
});
}
You can concatenate the selector by using "+" operator or `` if you are using es6.
// ES5 ->
alert('Please fill out the fields - ' + selector);
//ES6 -> alert(`Please fill out the fields - ${selector}`);

Determining if a user input field is empty

I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.
function Script() {
var G = document.getElementById("gradevalue").value
if (G == null || G == undefined) {
window.alert("Please input a grade");
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()">
I'm very new at this, so please don't be too harsh.
I think, you can simply check it like:
if (!Number(G)) {
window.alert("Please input a grade");
}
this is going to be true if G is null, undefined, '', 0, false and NaN and any strings that are not converted to numbers.
function CheckGrade () {
var G = document.getElementById("gradevalue").value;
if(!Number(G)) {
window.alert("Please input a grade");
} else {
//your code here, maybe some othe validation logic
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="number" min="1" max="10"/>
</label>
<input type="button" value="GRADE!" id="nota" onclick="CheckGrade()">
UPDATE Added a code sample and minor mistakes.
Checking !G || G == 0 seems to do the job:
function Script() {
var G = document.getElementById("gradevalue").value
if(!G || G == 0) {
window.alert("Please input a grade");
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()">
Note that you may also want to check for > 11 values:
if (!G) {
window.alert("Please input a grade");
} else if(G == 0 || G > 10) {
window.alert("Please input a grade between 1 and 10");
}
You are also must there, in JavaScript you can just check if the variable has a value assigned to it, if it doesn't then the bool expression will be false. I have done a quick CodePen with the working code https://codepen.io/robdavis/pen/bRVxdm
function Script() {
var g = document.getElementById("gradevalue").value
if (!g) {
window.alert("Please enter a Grade");
}
}

jQuery validation number

I have a single input field where the user can only enter a number between 2 AND 50. Anything above or below is invalid. It also MUST be a numeric value.
What I have so far is this:
$('#searchTimes').click(function() {
if($('#replyNumber').val()<=0) {
alert("Please select a value greater than 0 for number of guests");
$('#replyNumber').focus();
return;
}
if($('#replyNumber').val()>=51) {
alert("Please select a value less than or equal to 50 for number of guests");
$('#replyNumber').focus();
return;
}
if(isNaN($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus();
return;
}
});
Is there a better more efficient way of writing that ^.
Also ... IF all of those IF statements are not true then I need to perform another function. How can I add that in?
_isValidNumber(number) {
var message;
var isValid;
switch(number){
case number >= 51:
message = "Please select a value less than or equal to 50 for number of guests";
isValid = false;
case number <= 0:
message = "Please select a value greater than 0 for number of guests";
isValid = false;
case isNumeric(number):
var message = "Please enter a numeric value only";
isValid = false;
default:
return true;
}
alert(message);
$('#replyNumber').focus()
return isValid;
}
function isNumeric(num){
return !isNaN(num)
}
var number = $('#replyNumber').val();
var numberIsValid = _isValidNumber(number);
I would try to abstract out duplicate code, like this:
<input id="replyNumber" >
<button id="searchTimes">click</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#searchTimes').click(function() {
var val = $('#replyNumber').val()
if(val<=0) showErr("Please select a value greater than 0 for number of guests");
else if(val>=51) showErr("Please select a value less than or equal to 50 for number of guests");
else if(isNaN(val))showErr("Please enter a numeric value only");
});
function showErr(msg){
alert(msg);
$('#replyNumber').focus();
}
</script>
This is what you need :D
$('#searchTimes').on('click',function() {
var do_function = 1;
if (!$.isNumeric($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() < 2) {
alert("Please select a value at least 2 for number of guests");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() > 50) {
alert("Please select a value no more than 50 for number of guests");
$('#replyNumber').focus().select();
} else {
do_function = 0;
}
if (do_function) {
call_some_function();
}
});
Good luck!
Use HTML5 min and max attributes and an input of type number (which covers the numeric part you mentioned). Use rangeOverflow and rangeUnderflow Validity Properties to check your input and present the proper error (or custom error) messages.
Try the below snippet using the following values (null (empty input),1,55) and check the custom error messages created.
function validateInput() {
var txt = "";
if (document.getElementById("inp1").validity.rangeOverflow) {
txt = "Value larger than acceptable!";
}
if (document.getElementById("inp1").validity.rangeUnderflow) {
txt = "Value smaller than acceptable";
}
if (document.getElementById("inp1").validity.valueMissing) {
txt = "Please type a number!";
}
document.getElementById("output").innerHTML = txt;
}
document.getElementById("btn").addEventListener("click", function(){
validateInput();
});
<form>
<input type="number" id="inp1" name="numberInput" min="2" max="50" required>
<button id="btn">go</button>
</form>
<div id="output"></div>

Form Validation

JS:
validate document.forms();
if (document.forms[0].userAge.value == "") {
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value < 5) {
alert("Your age input is not correct.");
return false;
}
if (userage == isNumber) {
alert("Your age input is not correct.");
return false;
}
alert("Name and Age are valid.");
return true;
HTML:
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
</div>
If this is the code I have, how would I make it so that if someone were to enter a non number in the age text box an alert would come up saying " Your input is not correct"?
Edit: I originally suggested using parseInt with isNaN() to test if the input was non-numeric. Well, it seems that using a regex is preferrable not only formatching cases like "4a" correctly, but it's actually faster in many cases (surprise!).
I mocked up some HTML with a button to illustrate.
HTML:
<form>
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
<input type="button" id="test" name="test" value="Test" />
</form>
JavaScript:
function validateForm() {
// get the input value once and use a variable
// this makes the rest of the code more readable
// and has a small performance benefit in retrieving
// the input value once
var userAge = document.forms[0].userAge.value;
// is it blank?
if (userAge === "") {
alert("Age field cannot be empty.")
return false;
}
// is it a valid number? testing for positive integers
if (!userAge.match(/^\d+$/)) {
alert("Your age input is not correct.")
return false;
}
// you could also test parseInt(userAge, 10) < 5
if (userAge < 5) {
alert("Your age input is not correct.")
return false;
}
alert("Name and Age are valid.");
return true;
}
// trigger validateForm() however you want, I did this as an example
document.getElementById("test").onclick = validateForm;
​Here is a jsFiddle to demonstrate: http://jsfiddle.net/willslab/m2spX/6/
About the regex: userAge.match(/^\d+$/) returns true if userAge only contains a positive integer. The beginning / and ending / indicate a regular expression literal. \d indicates ASCII digits only. + matches one or more occurrences of the previous pattern (digits in this case). ^ indicates match from the beginning, and $ indicates match until the end. So /^\d+$/ is a regex literal matching only ASCII digits from beginning to end!
Also note that you can combine the last two if statements using an OR operator (||). I left these isolated in case you want to give each one a unique validation message.
It would look like this:
if (!userAge.match(/^\d+$/) || userAge < 5) {
alert("Your age input is not correct.")
return false;
}
Feel free to ask any questions about the code and I will explain. I hope that helps!
I recommend you to use the following Javascript which will not allow non-numeric characters in the text field.
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
return true;
}
<input type="text" id="userAge" name="userAge" onkeypress="return isNumberKey(event);">
Try this solution
<script language="javascript">
function validate(){
alert("validate ..."+document.forms[0].userAge.value);
if (document.forms[0].userAge.value == ""){
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value<5){
alert("Your age input is not correct.");
return false;
}
//provide a way to validate if its numeric number..maybe using regexp
//if (isNumeric(userAge)){
// alert("Your age input is not correct.");
// return false;
//}
//alert"Name and Age are valid."
return true;
}
</script>
The HTML should be
<form>
<div><label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" onblur="validate()"/>
</div>
</form>
use the code below
if(isNaN(document.forms[0].userAge.value)){
alert('This is not a number');
}

Categories