Check the length of the number entered in a textbox - javascript

I want to write in text box and check if is integer and less than 16 numbers. I have the following JavaScript codes.
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else {
return true;
}
}
</script>
<form method="post" action="" onsubmit="return doCheck('number');">
national id=<input type="text" name="nat" id="number">
<input type="submit" name="submit">
</form>

document.getElementById(field).value.length

you can find the length of string inside the text box using this
function doCheck(field) {
var len = document.getElementById("number").val().length;
if(parse.Int(document.getElementById(field).value) && len < 16) {
return true;
}
else {
alert('your alert');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
}

be sure you parse it as an integer.
function doCheck(field) {
var input_value = document.getElementById(field).value;
if(isNaN(input_value) || parseInt(input_value,10) != input_value || input_value.length < 16) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else{
return true;
}
}

isNAN() checks whether a number is an illegal number of any type, not only integer. So you have to use something else there, a regular expressions maybe.
To get the length of the field you can simply use:
document.getElementById(field).value.length

Related

jQuery Greater than and Smaller than check

This is my form:
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
And this my jQuery that's not working:
$('.fms-quote-form').submit(function() {
if ( $('#fms-zip').val() >= 90000 AND <=96162 ) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
How do I (i) check that the value of #fms-zip is greater than 90000 and smaller than 96162 to submit the form, and (ii) redirect the user to another website if any other value is entered?
Look forward to your input :)
Always check the error console - you're assuming syntax that is faulty. AND will be throwing an error - you need &&.
What's more, you can't just specify your higher number and assume JavaScript will know to compare it against the same subject value you compared the lower value against - you have to repeat the subject.
let val = parseInt($('#fms-zip').val());
if (val >= 90000 && val <= 96162 ) { //<-- note 2 references to #val
As #Alessio Cantarella points out, you also need to cast the value to a number - reading the field's value returns a string.
To check if ZIP is greater than 90000 and smaller than 96162, you need to use:
parseInt function to convert #fms-zip's value to an integer
&& logic operator to check that both conditions are valid.
$(function() {
$('.fms-quote-form').submit(function() {
let zip = parseInt($('#fms-zip').val());
let isZipValid = zip >= 90000 && zip <= 96162;
if (isZipValid) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
You can try like this -
$(function() {
$('.fms-quote-form').submit(function() {
var valueZip= parseInt($('#fms-zip').val());
if (valueZip >= 90000 && valueZip <= 96162) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

Minimum character count text box

my code isn't working for some reason..here it is:
html:
<input type="text" name="post" maxlength="140" />
and for javascript:
var inpt = document.getElementsByName("post")[0];
// var inputValue=document.getElementById(post).value;
if (inpt.value < 10) {
return false;
alert("Post must be longer than 10 characters.");
} else {
return true;
}
i tried it with and without quoting the second line and both do nothing. also i made sure to change inpt.value to inputValue.length when i unquoted the second line.
There are 2 problems
var inpt = document.getElementsByName("post")[0];
//need to test the length
if (inpt.value.length < 10) {
alert("Post must be longer than 10 characters.");
//return after the alert
return false;
} else {
return true;
}
Also make sure that the script is triggered on an event
function validate() {
var inpt = document.getElementsByName("post")[0];
//need to test the length
if (inpt.value.length < 10) {
alert("Post must be longer than 10 characters.");
//return after the alert
return false;
} else {
return true;
}
}
<form onsubmit="return validate()">
<input type="text" name="post" maxlength="140" />
<button>Save</button>
</form>
Put the alert before the return statement.

javascript validation numerical

Hi sorry i'm still pretty new to javascript.
I've developed a form in HTML and now i'm attempting to add javascript to validate the form.
So far i have simple javascript to make sure each element is filled in,
if (document.order.suburb.value=="")
{
alert("Suburb Cannot Be Empty")
return false
}
if (document.order.postcode.value=="")
{
alert("Postcode Cannot Be Empty")
return false
}
I then have javascript to validate the length of some of the elements,
if (document.order.telephone.value.length < 10)
{
alert("Invalid Telephone Number")
return false
}
Now i'm trying to validate numeric values in the telephone number part but it's not executing correctly, it's like the code is just ignored when it's being executed.
var digits="0123456789"
var temp
var i
for (i = 0 ; i <document.order.telephone.value.length; i++)
{
temp=document.order.telephone.value.substring(i,i+1)
if (digits.indexOf(temp)==-1)
{
alert("Invalid Telephone Number")
return false
}
}
Thanks for reading and thanks for the help :) been stuck on this issue for weeks and have no idea what i'm doing wrong, i tried to code on a separate document with another form and it seemed to work fine.
EDIT
Code for validation for digits in postcode
var post = document.order.postcode.value.replace(white,'');
if(!post){
alert("Post code required !");
return false;
}
post = post.replace(/[^0-9]/g,'');//replace all other than digits
if(!post || 4 > postcode.length) {
alert("Invalid Postcode !");
return false;
}
You may try this example:
var validate = function() {
var white = /\s+/g;//for handling white spaces
var nonDigit = /[^0-9]/g; //for non digits
if(!document.order.suburb.value.replace(white, '')) {
alert("Suburb required !");
return false; //don't allow to submit
}
var post = document.order.postcode.value.replace(white, '')
if(!post) {
alert("Post code required !");
return false;
}
post = post.replace(nonDigit,'');//replace all other than digits
if(!post || 6 > post.length) { //min post code length
alert("Invalid Post code !");
return false;
}
var tel = document.order.telephone.value.replace(white, '');
if(!tel) {
alert("Telephone required !");
return false;
}
tel = tel.replace(nonDigit,'');
if(!tel || 10 > tel.length) {
alert("Invalid Telephone !");
return false;
}
return true; //return true, when above validations have passed
};
<form onsubmit="return validate();" action="#" name="order">
Suburb: <input type="text" id="suburb" name="suburb" ><br/>
Post code: <input type="text" id="postcode" name="postcode"/><br/>
Telephone: <input type="text" id="telephone" name="telephone"/><br/>
<input type="reset"/><input type="submit"/>
</form>
Here is a FIDDLE that will give you something to think about.
You could handle this task in hundreds of ways. I've just used a regex and replaced all of the non-numbers with '' - and compared the length of two variables - if there is anything other than a number the length of the regex variable will be shorter than the unchanged mytelephone.
You can do all kinds of "validation" - just me very specific in how you define "valid".
JS
var mysuburb, mypostcode, mytelephone;
$('.clickme').on('click', function(){
mysuburb = $('.suburb').val();
mypostcode = $('.postcode').val();
mytelephone = $('.telephone').val();
console.log(mysuburb + '--' + mypostcode + '--' + mytelephone);
if(mysuburb.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('Suburb is required');
return false;
}
if(mypostcode.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('postode is required');
return false;
}
if( mytelephone.length < 1 )
{
$('.errorcode').html('');
$('.errorcode').append('telephone number is required');
return false;
}
if( mytelephone.length != mytelephone.replace(/[^0-9]/g, '').length)
{
$('.errorcode').html('');
$('.errorcode').append('telephone number must contain only numbers');
return false;
}
});

Two fields validation

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" onsubmit="return validate();" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<input type="text" id="course_desc" name="course_desc" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_desc();">
<label id="course_desc_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate_course_desc(){
var TCode = document.getElementById('course_desc').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate(){
return validate_course_name();
return validate_course_desc();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on two field but the problem is if i give first input field valid input and second invalid form get submitted where am i doing it wrong? ...i am very new to this web so any help will be appreciated:)
UPDATED ANSWER:
Fine! Just to be different =)
One line, should validate both fields regardless if the validate_course_name() returns false.
JSFiddle: http://jsfiddle.net/fVqTY/3/
function validate()
{
return (validate_course_name() * validate_course_desc()) == true;
}
Let false = 0, true = 1. Now do the math :)
function validate(){
var value1 = validate_course_name();
var value2 = validate_course_desc();
if(value1 == true && value2 == true)
return true;
else
return false
}
or You can use
function validate(){
var validate = true;
var TCode = document.getElementById('course_name').value;
var TCode1 = document.getElementById('course_desc').value;
if(! /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
if(! /[^a-zA-Z1-9 _-]/.test( TCode1 ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
return validate;
}
and then call this function directly
In this function, You should return only once. So what happens here is that when validate_course_name() gets executed, control is already returned to the calling routine. validate_course_desc() line won't execute.
function validate(){
return validate_course_name();
return validate_course_desc();
}
You should do this:
function validate(){
var bol1 = validate_course_name();
var bol2 = validate_course_desc();
if(bol1 == true && bol2 == true)
return true;
else
return false;
}
Your validate method as given below will return as soon as the first validate method (validate_course_name) is called so it will not execute the validate_course_desc method.
function validate(){
return validate_course_name();
return validate_course_desc();
}
The solution is to execute both the validate method and summarise them to create the return value as given in the above answers
change the function validate()
function validate()
{
if(validate_course_name() && validate_course_desc())
{
return true;
}
return false;
}
Once return statement is executed in a function, other statements that are following return statement does not work.
Therefore every time, validate_course_name() function is called , a bool value is returned and the function validate_course_desc() is not even called/executed.
Therefore, the validate function returns true if validate_course_name() is true and false if validate_course_name() return false.Hence , When you give first field valid input and second invalid, form get submitted.
the validation of both inputfields is the same, so you can make one validation function which takes an element-id as parameter:
function validateInputfield(id){
var TCode = document.getElementById(id).value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById(id).innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
return true;
}
}
Then you can use the function validate() to check if both inputfields are valid:
function validate() {
if (validateInputfield('course_desc_info') == true &&
validateInputfield('course_name_info') == true) {
return true;
} else {
return false;
}
}

Categories

Resources