JavaScript validating input only contains integers on submit - javascript

I've been trying for a bit to find a good way to go about this. Here's the trick this is being developed for IE6, so HTML5 is not supported (which is what is making this a pain, and why the button is actually a span). I need to allow all input into the input element but on submit i need to verify that the input is an integer and if it contains alpha characters or decimals throw an error.
<table id="studentIdInputTable">
<tr><td colspan="3"><hr class="style-hr" /></td></tr>
<tr><td><span class="underline bold">Selection 1</span></td>
<td class="center"><span class="small-text">Employee ID</span></td>
</tr>
<tr><td>Please enter your Student ID to <span class="bold italic">start your registration process</span></td>
<td class="center"><input type="text" maxlength="11" id="tbNewStudentId" /></td>
<td> <span id="btnNewStudent" class="validation-button">Start</span></td></tr>
</table>
I have javascript native to the HTML page as below
function CheckNewStudentId(){
var newStudentID = $("tbNewStudentId").val();
newEmployeeID = parseInt(newEmployeeID, 10);
var isNum = /^\d+$/.test(IDnumber);
if (isNum == false) {
alert(IDnumber + " is not a valid student number. Please enter only numbers 0-9, containing no alphabetical characters.");
}
}
It would be easier if this was for a more updated browser platform. Any ideas how I can go about this?
Edit***
For reference to other users this was solved using this function
function validIdCheck(Input){
if(Number.isInteger(Input)==false){
alert("This is not a valid ID");
}
}
connected to this jQuery click function
$("#btnNewStudent").click(function(){
var newStuId = $("#tbNewStudentId").val();
newStuId=parseInt(newStuId);
validIdCheck(newStuId);
});

To check if a number is an integer try this. It returns a boolean.
Number.isInteger(yourNumber)
docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

Using part of your code:
function validateStudentId(id) { return /^\d+$/.test(id) }
This will return true if it is a number or combination of numbers from 0 to 9.
If the id can not start with a 0, try this:
function validateStudentId(id) { return /^([1-9]|[1-9]\d+)$/ }
Quick explanation:
^ starts with
[1-9] digit between 1 and 9
| or
\d digit (0 to 9)
+ occurs at least once and up to unlimited times
$ ends with
Test it here

Related

Comma separated step for float number input

I want to comma seperated value for my input box. For Example 2100000.90 will be 2,100,000.90. What I achieved is 2100000.90 to 2,100,000 from some Solution in Stack overflow
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
And My Javascript is
document.getElementById('salary').addEventListener('input', event =>
event.target.value = (parseInt(event.target.value.replace(/[^\d]+/gi, '')) || 0).toLocaleString('en-US')
);
I want both comma separated and value after point.
Thanks in advance
Your logic is defeated by its own.
Here is what you are currently doing:
ask the user to input a series of digits and only digits
parse the input into an integer
format the integer in the en-US locale
what will happen when the user tries to input a decimal point?
It will automatically be removed by the regex replace.
What you need to do is the following:
Allow the user to input digits and decimal points
That will mess up if the user types more than one decimal point, but that can be detected and dealt with later
Try to detect if the input is a valid number or not
if not, then provide a negative feedback to the user
if yes, then provide a positive feedback
most important: the process of converting text to number will get rid of the decimal point if it is the last character in the input box. The user will not see the dot since the conversion from text to number will see that it is the last thing and it's not affecting the number, so it is removed, and the user doesn't know why.
Therefor, it is essential to add the "dot" back if it is the last thing typed by the user.
document.getElementById('salary').addEventListener('input', event => {
event.preventDefault();
// allow only digits and dots
let text = event.target.value.replace(/[^\d\.]/gi, '');
// check if last character is a dot
let lastCharIsAdot = text.substr(text.length - 1, 1) === ".";
// try to check if input text is a valid number
if (isNaN(text)) {
// if not, then give feedback to the user
event.target.classList.remove('valid');
event.target.classList.add('invalid');
} else {
// if yes, then give positive feedback
event.target.classList.remove('invalid');
event.target.classList.add('valid');
// format number
event.target.value = Number(text).toLocaleString("en-US");
// this will remove the dot if it is the last thing input
// therefor, we need to put it back
if (lastCharIsAdot) event.target.value += ".";
}
});
.valid {
background-color: lightgreen;
color: darkgreen;
}
.invalid {
background-color: pink;
color: maroon;
}
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
You can try this
parseInt(number, 10).toLocaleString()
here is also the link from mozilla docs about Number.prototype.toLocaleString() method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
This function help you :
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
Output :
numberWithCommas(88888888.88)); // 88,888,888.88

format numbers of RUT with simple javascript or jquery

I have a form where chilean customers need to write their security number ( RUT )
the format can be with 1.234.567-8 for old people or 12.345.678-9 for younger people
What I need is that when they type down their number the input text change as soon as they type down and start formatting the number with the two dots and - like in the example above
I created this code
<input type="text" class="inputs" name="cliente" id="cliente"
onkeydown = "this.value = this.value.replace( /^(\d{1})(\d{3})(\d{3})(\w{1})$/, '$1.$2.$3-$4')" >
It works almost good but only with 9 digits RUTs but not with 8 digits RUTs, any idea how to accomplish this ?
This logic removes any - or . you previously put in it, or the user put in it, and then performs the reformatting. It also fires on keyup rather than keydown as the new value would not have been added yet on the keydown.
function formatCliente (cliente) {
cliente.value = cliente.value
.replace(/[^0-9]/g, '')
.replace( /^(\d{1,2})(\d{3})(\d{3})(\w{1})$/, '$1.$2.$3-$4')
}
<input type="text" class="inputs" name="cliente"
id="cliente" onkeyup="formatCliente(this)">
i've made an correction to accept a RUT that's end with letter (like 8.345.434-k or 20.432.345-k)
function formatCliente (cliente) {
cliente.value = cliente.value
.replace(/[^0-9\dkK]/g, '')
.replace( /^(\d{1,2})(\d{3})(\d{3})(\w{1})$/, '$1.$2.$3-$4')
}

How can I perform math on last x characters of string and update text box on the fly?

I have an app where a user scans or types in a starting barcode, and the ending barcode is automatically calculated based on a quantity value.
It works fine when the starting barcode is entirely numeric, it does the math and includes leading zeroes so the end code is the correct length.
My problem is that some small percentage of the barcodes are not entirely numeric.
The barcodes are 14 characters long. The last 5 characters will always be numeric and quantities will rarely exceed a few hundred and never go high enough that we spill into the 6th digit.
I'm not a javascript expert by any means, and just getting what I have now working strained my skills -- I'm hoping the community here can help me out :)
Here's the code I'm working with:
$(document).ready(function() {
//leading zero fill function for barcodes
function pad(num, size) {
var s = "00000000000000" + num;
return s.substr(s.length - size);
}
//Function to do BC math: starting number + quantity -1 (since it's inclusive) = end.
function updateCode() {
var quantity = $(this).closest('tr').find('.quantity').val();
var barstart = $(this).closest('tr').find('.barstart').val();
var end = pad(parseInt(barstart, 10) + parseInt(quantity - 1, 10), 14);
$(this).parent().next().find('.barend').val(end);
}
$(document).on("change, keyup", ".barstart", updateCode);
});
Edit Trying to insert the HTML again:
<script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
<table id="formtable">
<tr>
<td><input class="quantity" size="6" id="qty_1" name="qtyid_1" value="123" type="text"></td>
<td><input class="barstart" size="15" maxlength="14" id="barstartid_1" name="barstart_1" value="" placeholder="Barcode Start" type="text"></td>
<td><input class="barend" size="15" maxlength="14" id="barendid_1" name="barend_1" value="" placeholder="Barcode End" type="text"></td>
</tr>
</table>
Here's a jsfiddle: https://jsfiddle.net/g1p2xh6y/1/
The users can live without it, but it'll save them some headaches (and help me make a good impression - this is a new gig) if I can get it working, so I greatly appreciate any help the community can offer :)
Thanks!
Many thanks to #admcfajn - I didn't know the slice() function existed, and that resolved it for me. I had to move the zero padding to the suffix, and remove it from the end value, but since it's pulling the prefix instead of doing math, that's no problem.
Here's the updated function:
function updateCode() {
var quantity = $(this).closest('tr').find('.quantity').val();
var barstart = $(this).closest('tr').find('.barstart').val();
var barprefix = barstart.slice(0,barstart.length-5);
var barendsuffix = pad(parseInt(barstart.slice(-5),10)+parseInt(quantity-1,10),5);
$(this).parent().next().find('.barend').val(barprefix+barendsuffix);
}

Javascript strip after X characters prior to form submit

UPDATE** Using the solutions provided below I added this with no luck?
<script>
$('.LogIn_submit').on('click',function(){
var value=$('#Log_In_group_2_FieldB').val();
value=value.replace(/^\s\d{6}(?=\-)&/, '')
alert(value);
});
</script>
Here are the form elements if, hoping it's a simple fix:
<input id="Log_In_group_2_FieldB" name="Log_In_group_2_FieldB" type="password" value="<?php echo((isset($_GET["invalid"])?ValidatedField("login","Log_In_group_2_FieldB"):"".((isset($_GET["failedLogin"]) || isset($_GET["invalid"]))?"":((isset($_COOKIE["RememberMePWD"]))?$_COOKIE["RememberMePWD"]:"")) ."")); ?>" class="formTextfield_Medium" tabindex="2" title="Please enter a value.">
<input class="formButton" name="LogIn_submit" type="submit" id="LogIn_submit" value="Log In" tabindex="5">
/***** Beginning Question ******/
Using this question/answers's fiddle I can see how they used javascript like this:
$('.btnfetchcont').on('click',function(){
var value=$('#txtCont').val();
value=value.replace(/^(0|\+\d\d) */, '')
alert(value);
});
I currently have a value that starts with 6 characters, ends in a dash and the up to 3 digits can follow the dash.
Exmaple 1: 123456-01
Example 2: 123456-9
Example 3: 123456-999
I've tried to insert a - in the value.replace cod with no luck. How do I remove the - and any values after this on submit so that I'm only submitting the first 6 digits?
Seems that you want to have only first 6 characters from the string.
Use .split() or substring(start, end) to get the parts of string.
var string = "123456-01";
console.log(string.split('-')[0]);
console.log(string.substring(0,6));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use split instead of regex
value=value.split("-")[0];
fix for your regex
/(-[0|\+\d\d]*)/g
function extractNumber(value){
return value.replace(/(-[0|\+\d\d]*)/g, '');
}
console.log(extractNumber("123456-01"));
console.log(extractNumber("123456-9"));
console.log(extractNumber("123456-999"));
Edit: the .split('-') answer is better than the following, imo.
Assuming you always want just the first 6 characters, something like this should do what you want:
$('.btnfetchcont').on('click',function(){
var value = $('#txtCont').val();
value = value.substr(0, 6);
alert(value);
});
or combine the two lines:
var value = $('#txtCont').val().substr(0, 6);
Read about .substr() here.
If you want to get everything before the dash, do something like this:
var value = $('#txtCont').val().match(/(\d*)-(\d*)/);
value is now an array where value[0] is the original string, value[1] is every digit before the dash, and value[2] is every digit after the dash.
This works for digits only. If you want any character instead of just digits, replace \d with .. i.e: .match(/(.*)-(.*)/).

Javascript not validating password in Form

Hi I have looked around online and I am aware that similar questions have been asked, however, I am unable to find a suitable solution to my problem. I need this code to be password validated, the problem is that I'm not directly working with an <input> field therefore I've been unable to figure out how to implement JS.
Here is the HTML (it's implemented using ruby-on-rails, this is all the 'HTML' side that I can see (full code in fiddle below))
<form accept-charset='utf-8' method='post' name="form" action='register' class="registerform" onsubmit="return validate_form()">
<h3 class="registernospace">Contact Information</h3>
<table>
<tbody>
<tr><td class="registerrowspace" colspan="2">The Password must be at least 6 characters long and should contain a mixture of lower case letters, upper case letters, and numbers.<br />The Confirm Password must match the Password.</td></tr>
<tr><th class="registerrowspace">Password</th><td id="password1" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Confirm Password</th><td id="password2" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Date of Birth</th><td class="registerrowspace">
</tbody>
</table>
<% end %>
<input type='hidden' name='register_submitted' value='yes'/>
<p><input type='submit' class="button" value='Register Now' /></p>
</form>
And I have tried Implementing some JS (but being unfamiliar with the language I haven't been able to get it working, but I was trying to do something like this:
<script type="text/javascript">
function validate_form()
{
var passw = document.getElementById('password1').value;
if(passw.value.length < 6 ) {
alert("Error: Password must contain at least six characters!");
form.password.focus();
return false;
}
return true;
}
</script>
So I was hoping it validates and raises a message if its blank, if its < 6 chars and if it does not include a Uppercase and a number. Although I'm aware I haven't introduced the latter in the code, I couldn't even get the <6 to work.
Also I have other validations (which were built by default which work) and you can see the full:
Fiddle code
Live Website
if(passw.value.length < 6 ) {
should be
if(passw.length < 6 ) {
because you already get its value
var passw = document.getElementById('password1').value;
UPDATE:
password1 is <td> id not of password feild
i just check your link, it was giving error passw is undefined in console, you password field id is password-input-0, so use
var passw = document.getElementById('password-input-0').value;
^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$
---
^.* : Start
(?=.{6,}) : Length
(?=.*[a-zA-Z]) : Letters
(?=.*\d) : Digits
(?=.*[!#$%&? "]) : Special characters
.*$ : End
function validatePassword() {
var newPassword = document.getElementById('changePasswordForm').newPassword.value;
var regularExpression = ^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$/;
alert(newPassword);
if(!regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}
}
Instead of using if(passw.value.length < 6 ) use if(passw.length < 6 ) you have already value of password you only need to check for size.
Also, Your textfield name is wrong. 'Password1' is td name not password textfield. Please check and correct.
if(passw.length < 5 ) //here should be 5
Page refreshes when you click the button :you don't call e.preventDefault(); I think you should listen 'submit' event. In the 'listen' function you may validate the length of the input and prevent it's default behavior.

Categories