JavaScript to only allow numbers and certain length and no periods - javascript

I need help with a piece of JavaScript. I have this code:
<script>
function FilterInput(event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNotWanted = (keyCode == 69);
return !isNotWanted;
};
function handlePaste(e) {
var clipboardData, pastedData;
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text').toUpperCase();
if (pastedData.indexOf('E') > -1) {
e.stopPropagation();
e.preventDefault();
}
};
</script>
I would like to limit the user's input to only 5 digits. For example, for this entry box, I'd like no more than five numbers to be allowed (12345 for example) and no periods:
<div class="col-md-3">
<div class="form-group">
<label>Customer Number</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input name="CustomerNumber" type="number" class="form-control" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)" required>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
How would I achieve this? I know for
type="text"
it allows limiting spaces by using "maxlength."

One way to do this is to trap the input, check if it passes your validation checks, and if so, proceed, if not, set it to the last known good value, like so:
var oldValue = "";
// listen for "input" event, since that handles all keypresses as well as cut/paste
document.getElementById("myInput").addEventListener('input', function (event) {
var input = event.target;
if (validateInput(input.value)) {
// update old value with new value
oldValue = input.value;
}
else {
// set value to last known valid value
input.value = oldValue;
}
});
function validateInput(str) {
// check length, if is a number, if is whole number, if no periods
return /^[0-9]{0,5}$/.test(str);
}
Test: <input type="text" id="myInput"/><br/>
Try typing/pasting invalid input

all the answers given here previously before mine are all outdated previous
I think solving this question is best answered by
Javascript slice is used to maintain character length
Javascript replace to maintain only numbers are taken
javascript oninput event to prevent the user does not use copy and paste to inject / input invalid character javascript.
<script>
function validate(field) {
let val = field.value;
let data = val.replace(/[^0-9]/g, "");
field.value = data.slice(0,16);
}
</script>
<label for="atmno">Payment card Number</label>
<input name="atmno" type="text" oninput="validate(this)">
I briefly described the answer on an article I wrote here: https://shopinson.com/javascript/javascript-validates-payment-card-number/

Well you could instead of choosing a number type input, use a text type input, where the maxlength attribute works and throw an error with JavaScript if the value is not a number. Like,
if(isNaN(input.value)){ // error code here }

A pure js and dom manipulation solution
Adding an Id attribute for simplicity
<input type="number" id="in" />
We're going to listen for the keypress event and do nothing if the max length is met or a period is entered, i'm using 5 as the max.
let input = document.getElementById('in');
input.addEventListener('keypress',function test(e){
if(input.value.length==5 || e.key=='.')
e.preventDefault();
});

You can run a validation check in your filterInput method.
document.querySelector('.input-group .form-control').addEventListener('keyup', function() {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNotWanted = (keyCode == 69);
if (this.value.length > this.maxLength) {
this.value = this.value.slice(0, this.maxLength);
}
return !isNotWanted;
});
<div class="col-md-3">
<div class="form-group">
<label>Customer Number</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
<input maxlength="5" name="CustomerNumber" type="number" class="form-control" required>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->

Related

I'm trying to validate multiple HTML Form inputs with javascript, and change css for invalid ones, what is the best way to do this?

I'm trying to validate an HTML form, trying to check if answers are filled in, and an e-mail is an actual e-mail adress. I want to proceed when all fields are valid. When some fields are not valid, change the css in to another class (so it becomes red to show that it is wrong.)
I have tried to validate each input seperately, but i believe there should be an easier way. Can somebody show me?
Current HTML:
<div class="form-group" id="stage1">
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
</div
I can't use HTML default validation, since I have created a multi-step form.
Thanks in advance,
Brandon
You can iterate through inputs this will assist validating your messy items:
window.onload = () => {
const allInputs = document.querySelectorAll(".form-control"); // or you may assign custom class or select by input tag..
let isAllvaild = true;
allInputs.forEach((element) => {
if (!validateAll(element.value, element.type)) { isAllvaild = false; break; }
});
if (isAllvaild) {
afterValidation(); // to keep things clean
}
}
function validateAll(value, type) {
if (type === "text") {
} else if (type === "email") {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let ck = re.test(String(value).toLowerCase());
if (ck) {
// set errors here..
} else {
// maybe remove errors if added previously..
}
return ck;
} else if (type === "phone") {
} else if (type === "other") {
} // add whatever needed..
}
function afterValidation() {
// at this point each input contains valid data.. proceed to next step..
// document.querySelector("#my_id").classList.add("display-block");
// ..
}
you can validate based on their type, so i think u would have two functions, one for email and another one for text fields. for instance:
if(textValidation() && emailValidation()){
submit()
}
emailValidation(){
return email ? true : false
}
textValidation(){
return text ? true : false
}
What about that? It will let you loop through every input and you can also do some specific validations. I know, it is not the smartest function ever, but it can be useful. (ofc you should make some better checking for email pattern (regular expressions are good for that /^.+?#.+..+$/m) and registration number (regex could be cool for that too: /^[\d]*$/m)
function validateInputs ()
{
const inputs = document.querySelectorAll('div[class=row] input');
for (let index = 0; index < inputs.length; index++)
{
const input = inputs[index];
let valid = false;
if (input.value && input.value.trim() !== '')
{
//here you can add specific validations for each id, maybe you can also use switch here
if (input.getAttribute('id') === 'email')
{
//of course, email also need to validate, if dot is present, regular expression might be the best option
if (input.value.indexOf('#') !== -1)
{
valid = true;
}
}
else
{
valid = true;
}
}
if (!valid)
{
input.classList.add('error');
}
else
{
input.classList.remove('error');
}
}
};
window.addEventListener('load', function () {
document.querySelector('button').addEventListener('click', validateInputs)
});
input.error {
background-color: red;
}
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
<button>validate</button>
For fields like text you need to write your own validation, since it is totally up to you. But in case of fields like email or url you can use build in functions like the HTMLFormElement.checkValidity() method to see if the form contains a field that does not have a valid input, for example a input with type email and a value of foobar would return false from the validity check.
Then you can look inside the form and search for all inputs that are invalid with the :invalid selector in querySelectorAll(). It will return a NodeList with the invalid form elements inside of it.
const form = document.querySelector('form');
form.addEventListener('input', event => {
if (form.checkValidity() === false) {
const invalids = form.querySelectorAll(':invalid');
for (const input of invalids) {
console.log(`${input.id} is invalid`);
}
}
});
<form>
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="url" id="website" class="form-control" placeholder="Website*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</form>
You can use this code between a script tag :
const form = document.querySelector('form'); form.addEventListener('input', event => { if (form.checkValidity() === false) { const invalids = form.querySelectorAll(':invalid'); for (const input of invalids) { console.log(`${input.id} is invalid`); } } });
Or use a Bootstrap classes to validate your form

Minimum and Maximum length of User Input

I have a form in which a user enters a 13 digits numeric value and i try to use minlength attribute but its not working. So i try javascript and it works fine but when the focus losses from Input then the function onblur calling again and again. the code is under
HTML
<input type='number' id='cnc' pattern='[0-9]{13,13}' name='cnic' oninput="javascript: if (this.value.length > 13) this.value = this.value.slice(0, 13);" minlength="13" onblur="checkLength(this);" placeholder="Enter CNIC without dashes: e.g 6110122334455" class='form-control' required value="<?php echo isset($_POST['cnic']) ? htmlspecialchars($_POST['cnic'], ENT_QUOTES) : ""; ?>" />
Javascript
function checkLength(el) {
if (el.value.length != 13) {
alert("CNIC length should be 13 digits");
document.getElementById("cnc").focus();
document.getElementById("cnc").select();
}
Now i want that the control/cursor to the input field if user not entered 13 digit code and moves to other input field
Try this regex method to verify the Pakistani CNIC format:
jQuery('#cnic').blur(function(){
var input_text = jQuery(this).val(),
myRegExp = new RegExp(/\d{5}-\d{7}-\d/);
if(myRegExp.test(input_text)) {
//if true
jQuery('#cninc_msg').text('Correct');
}
else {
//if false
jQuery('#cninc_msg').text('Enter CNIC in correct format. 12345-1234567-1');
}
});
jQuery('#cnic2').blur(function(){
var input_text = jQuery(this).val();
if(input_text.length != 13 ){
jQuery('#cninc2_msg').text('Error');
}
else{
jQuery('#cninc2_msg').text('OK');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="cnic" name="cnic" placeholder="42212-1234567-1" />
<span id="cninc_msg"> </span>
Without Dashes simply check this
<input type="text" id="cnic2" name="cnic" placeholder="4221212345671" />
<span id="cninc2_msg"> </span>
This is just a basic example. You can use this on on key up or onkeyDown events as per your requirements.
minlength is not yet supported by any browser. Try this instead

Input type validations are not working for the very first time after page loads

I have a text box, in that I wants to allow only alphabets.
Below is my code :
state ={
NomName: '',
}
onlyAlpha(e) {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
render = () => {
return (
<label for="nominee">Nominee name</label>
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha.bind(this)} autoComplete="off"
maxLength="100"/>
)}
The input validations are not working (I am able to enter Numbers) at very first time after page loads. But once you cleared the field and try to re-enter the value it won't takes numbers (It works).
How can I make it run at each and every time.?
Please let me know if I am doing anything wrong.
I suggest you start using fat arrow functions. Make the onlyAlpha function like so:
onlyAlpha = (e) => {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
This would remove the usage of this.onlyAlpha.bind(this).
Also, I think you should pass the function to the onChange listener like so:
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha} autoComplete="off"
maxLength="100"/>

Provide hyphens between numbers as a formatting in Javascript

So I have a requirement to format a 9 digit number by providing hyphens in the appropriate places.If the number is 123456789 ,after formatting it has to be 123-45-6789.To achieve this,I have set the maxlength as 9 in HTML
<div class="form-group">
<label class="col-sm-2 control-label labelfont">SSN:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the SSN" id="SSN" name="SSN" data-bind="value: SSN" onkeypress="return onlyNumbers(event);" maxlength="9">
</div>
<label class="col-sm-4 labelfont errorMsg" id="Err_SSN">Enter the SSN</label>
</div>
and in the JS,Ihave the following code
var Provider = function () {
var self = this;
self.ProviderID = ko.observable("");
self.SSN = ko.observable("");
};
var blurred = false; //Prevent reformatting when Tab back in.
$("#SSN").blur(function () {
if ($(this).val().trim().length == 0) {
$("#Err_SSN").text("Enter the SSN");
$("#Err_SSN").show();
$(this).addClass('borderclass');
}
else {
if (!blurred) {
$("#Err_SSN").hide();
var SSN = $("#SSN").val();
$("#SSN").val(SSN.substring(0, 3) + "-" + SSN.substring(3, 5) + "-" + SSN.substring(5));
$("#SSN").removeClass('borderclass');
Provider.SSN($("#SSN").val());
blurred = true;
}
}
});
$(document).ready(function () {
ko.applyBindings(new Provider());
});
The above code works when I tab out after entering 9 digits in the relevant field,but as you may have already figured out,it does not work if I tab back in to edit the data.Now,I know the edit is not happening because the max length is 9 and hyphen is seen as one of the characters.But if I allow more than 9 digits in the field,the number could be considered as invalid.So,if you folks have a better way of achieving my requirement,please guide me.
You could remove the hyphen(s) when focusing back on the text field:
$("#SSN").focus(function(){
$(this).val() = $(this).val().replace(/-/g,"");
});
Not tested, but that's the idea.

How do I prevent invalid characters from being entered into a form?

For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?
This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.
function noNumbers(answer) { //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}
}
<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>
This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:
<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>
<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789#._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>
Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.
This is the function you are looking for
function validateAnswer(src) {
var questions = document.getElementById("questions");
var rule = questions.options[questions.selectedIndex].value;
if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}
just send the input field reference to the function and set it to onkeyup event instead:
<input type="text" name="answer" onkeyup="validateAnswer(this);" />
you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See
the fiddle
patern attribute support
workaround for unsupported browsers
You get the key being pressed from the event object passed to the handler.
input type="text" name="answer" onkeypress="validateAnswer(this, event);" />
function validateAnswer(element, event) {
if (event.charCode) {
if (/\d/.test(String.fromCharCode(event.charCode))) {
window.alert("You can not enter numbers in this field");
return false;
}
}
}
Googling for "onkeypress event" finds many examples of this.
Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />
Then you can define your validateAnswer like this:
function validateAnswer(elem){
elem.value = elem.value.replace(/[^\d]/g, '');
}
Here an example: http://jsbin.com/iwiduq/1/

Categories

Resources