Can anyone tell me what are the alternatives to validate user input? this is just a very basic code I wrote today.
there is a button coded in HTML
when the user click on it, it will prompt for input
the input is only numbers
var a, b;
function cal(){
a = prompt("enter the width");
while(isNaN(a) || a <= 0 || a > 1000){
alert("Invalid Input, enter it again!");
return cal();
}
b = prompt("enter the length");
while(isNaN(b) || b <= 0 || b > 1000){
alert("Invalid Input, enter it again!");
return cal();
}
result(a,b);
}
function result(a,b){
var perimeter = (2*a)+(2*b);
var area = (a*b);
document.write("Perimeter: "+perimeter+"<br>");
document.write("Area: "+area+"<br>");
}
One alternative is to use the new HTML5 input types and fall back to something like this
if the browser does not support the new input type yet.
<input type="number" min="1" max="1000" />
But don't forget you still must do server side validation!
There are many great resources online and on SO on how to do this.
HTML Text Input allow only Numeric input
You can use a regex in your confirms:
var ptrn=/\D/g; // 'D' is any non-digit
if(ptrn.test(b) || b <= 0 || b > 1000){
alert("Please enter only integers between 0 and 1000!");
return cal();
}
Related
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");
}
}
I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>
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;
}
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');
}
OK so i have this task that im not sure how to achieve. I have a text field that is only allowing the users to enter numeric values....I am validating on keypress to make sure that only numeric numbers are allowed
That works well
My problem is that the client wants text after the numbers to say " Miles" so if the user enters 100 they see "100 Miles"
I guess for usability. Does anyone know a good technique or jquery plugin to do this
In addition to a javascript solution, you may also want to look into the HTML 5 pattern attribute for <input>. For example, in modern browsers you could do something like:
<input name="miles" pattern="^\d+\s?[Mm]iles$" required>
Which requires no javascript at all :) Here's the relevant spec.
How about this:
$('input').keypress(function(e) {
if (e.which < 48 || e.which > 57) {
// not a number
return false;
}
// gets current entered numer
var number = this.value.split(' ')[0];
// adds new number
number = '' + number + String.fromCharCode(e.which);
this.value = number + ' miles';
return false;
})
It would be easier and I think clearer to do this in some sort of tag just outside of the textbox. Have a span directly below or something then update it on your keypress.
$('#textBox').keydown(function(){
// Validation code
$('#someSpan').html($(this).val() + " Miles");
});
How about this http://jsfiddle.net/TmxSN/1/
$(function(){
var timerOutId;
$('#inp').keypress(function(e) {
var key = e.which;
clearTimeout(timerOutId);
try{
if(this.value){
this.value = $.trim(this.value.match(/\d+/g)[0]);
}
}catch(e){}
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
}).keyup(function(e) {
var textBox = this;
if(this.value){
timerOutId = setTimeout(function(){
textBox.value = $.trim(textBox.value.match(/\d+/g)[0]) + " Miles";
}, 2000);
}
})
});
My problem is that the client wants text after the numbers to say "
Miles" so if the user enters 100 they see "100 Miles"
Then you can handle it in the onfocus and onblur event of your input type="text" like this.
Try this
<input type="text" min="0" max="1000" step="1" id="distance" placeholder="Enter the value in miles"/>
And Script
$(document).ready(function() {
//$("#distance").keypress(PassNumbersOnly);
$("#distance").focus(OnFocus);
$("#distance").blur(OnBlur);
});
function OnFocus() {
var $this = $(this);
if ($this.val().indexOf("Miles") != -1) {
$this.val($this.val().split(" ")[0]);
}
}
function OnBlur() {
var $this = $(this);
if ($.trim($this.val()) != "") {
$this.val($this.val() + " Miles");
}
}
Demo here: http://jsfiddle.net/naveen/EQEMr/
Tell your client that anyone with enough intelligence to use the web can understand:
<label for="distance">Distance in miles:
<input type="text" name="distance" id="distance"></label>
and that doing anything else is:
confusing for users
problematic as javascript may or may not be enabled/available
of zero practical use for the business as the value must be validated on the server anyway
the value requires additional processing at the server to remove the appended characters