Regex change in keyup handler to allow alphabets in specific location - javascript

I am using following validation to put autodash in my textbox .
$('input#txtReportingNum').keyup(function (e) {
this.value = this.value
.match(/\d*/g).join('')
.match(/(\d{0,2})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
});
Input = string_1-String_2-String_3
The above code does not allow me to enter alphabets . How can i change the above pattern to make String_2 and String_3 to allow both alphabets and numbers. Can anybody please help me to get this done ?
I want to make something like 89-e3-w323

Try something like this
$('input#txtReportingNum').keyup(function (e) {
this.value = this.value
.match(/[a-fA-F0-9]*/g).join('')
.match(/(\d{0,2})([0-9][a-fA-F])(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
});
Input = string_1-String_2-String_3

Related

jQuery to prevent user from inputting if regular expression is not matched by using preventdefault

Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched
Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)
var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
$("#" + (idOfElement)).on("keyup",function (e) {
var val=this.value
var k = e.keyCode
if(k==46 ||(k > 48 && k <97)){
console.log(k)
return discountRegex.test(val);
}
});
in the above code idOfElement is the id i get on whichever field i focus.
Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.
<input type="text">
$(document).ready(function(){
$("input").bind('keypress', function(e) {
var str = e.keyCode;
if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
alert('Invalid')
e.preventDefault();
} else {
alert('Valid');
}
});
});
You can check if the regex is matched and if not you can remove the last char like the example below
I updated the code with keydown example
Example

Detect/Prevent unicode (alt + numpad) characters in inputs using jquery

I'm struggling to prevent input of alt + numpad unicode characters.
The alt key doesn't seem to register on keyup and will enter the unicode character regardless. (try something like 'alt + 1' in the example code snippet below to see what I mean.)
I've tried something like the following that attempts to restrict non-numeric characters:
$("#myInput").on('paste keyup keydown change', function(event) {
var $input = $(this);
var value = $input.val();
// remove whitespace
value = value.replace(/\s+/g, '');
// remove unwanted characters
value = value.replace(/[^0-9]+/g, '');
$input.val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput" type="text">
Is there an event I should be looking for instead of the above 4? (paste keyup keydown change)
I was able to prevent them on the keypress event...
function noteKeyPress(event) {
if(event.code.slice(0,3) == 'Alt'){
event.preventDefault();
event.stopPropagation();
}
}
This page was a great help

Regular Expression max-length is not working

function test() {
var regex = new RegExp("^[0-9]{1,11}$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
It is correct to take only integer but max-length is not working. It takes more than 11 digits.
This kind of manual input validation is not how applications are usually written these days in HTML5. It is a throwback to the bad old jQuery days. It is a bad user experience to simply throw away keystrokes--the user has no idea what he is doing wrong, and may think his keyboard is broken. If you trap on the keyup event, you will also miss some scenarios, such as when the user has dragged and dropped text into the input box. Or if the user types CTRL+V to paste text into the box, you will end up looking at that keystroke instead of the characters pasted in.
HTML5 adds the pattern attribute to the input element which allows you to do regexp-based validation. This has a number of advantages. For instance, invalid entries can be styled using CSS with the :invalid pseudo-class. Invalid form entries will automatically prevent submits, and put up user-friendly balloons describing the specific problem.
In your case:
<input pattern="\\d{1, 11}">
Note that no ^ or $ anchors are required--they are implicit in this case.
No JS is required.
as you said:
I want to give permission only to write digits and max length should be eleven(11) digits.
you can:
use an <input type="number" maxlength="11" />
use a regex /^\d{1,11}$/
document.addEventListener('DOMContentLoaded', function() {
function valueIsValid(v) {
return /^\d{1,11}$/.test(v);
}
var foo = document.querySelector('#foo');
foo
.addEventListener('change', function() {
console.log('valid', valueIsValid(foo.value), foo.value)
})
;
});
<input id="foo" />
This is what I understood from your question. Try something like this.
var count = 0;
function test() {
var regex = new RegExp("^[0-9]{1,11}$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if(count<11){
if (!regex.test(key)) {
count=0;
event.preventDefault();
return false;
}
count++;
}
return false;
}

Javascript validation C#.NET

I am having a problem validating a textbox to not allow spacing. When the user enters a space I would like it to display an alert message and then clear the textbox, but the textbox doesn't clear. This is what I have so far.
function ValidateSpace () {
var SerNum = document.getElementById("txtbox1")
if (event.keyCode == 32) {
alert("This field may contain no spaces.");
document.getElementById ("txtbox1").value=""
}
}
I have users trying to put multiple entries in this space but it should only accept one. The textbox is for inventory purposes so it would change the nature of the data if I were to remove spaces
I suppose that you have to bind keyDown event on textbox
try this jquery code to remove live the spaces
$("#IdOfTheTextBox").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
If you can't use jquery try with this javascript function (onkeypress event of textbox)
function NoSpace() {
if (event.keyCode == 32) {
event.returnValue = false;
return false;
}
}
if you want to remove spaces after the input you can do this
var noSpaces = document.getElementById("txtbox1").value.replace(/\s/g, "");

Detect when text is entered into the textarea and change it correspondingly

I have a textarea where users can enter or paste email addresses of other people and send them an invite after pressing Submit button. Each email must be seperated with a comma and valid before the form is submitted - validation is taken care of by jQuery Validate plugin & multiemail method.
Problem
Some people paste email addresses directly from their email clients and those emails are often in a weird format - containing name and surname before the actual email, or the email is wrapped in < >. For example:
"The Dude" <the.dude#gmail.com>, "The Dudette" <thedudette193#gmail.com>
Question
What I want to do is to Extract all email addresses from bulk text using jquery, but I'm having problems integrating this piece of code to work with my textarea - I don't know where to start.
How could I use the code from the above answer to extract each email entered into the textarea after a comma is typed or when the focus is moved away from textarea? So if I paste "The Dude" <the.dude#gmail.com> and type , after it or switch focus away, the entered value would change to the.dude#gmail.com.
I'm guessing something like this :
var textarea = $('#emails');
textarea.on({
keyup: function(e) {
if (e.which === 188) check();
},
blur: check
});
function check() {
var val = $.trim(textarea.val()),
err = '';
if (!val.length) {
err = 'No input ?';
return;
}
var emails = val.split(','),
notvalid = [],
temp = [];
$.each(emails, function(_,mail) {
mail = $.trim(mail);
if ( mail.length ) {
var m = mail.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (m) {
temp.push(m);
}else{
temp.push(mail);
notvalid.push(mail)
}
}else{
temp.push(mail);
}
if (notvalid.length) err = 'Not valid emails : ' + notvalid.join(', ');
});
$('#error').html(err);
textarea.val((temp.length ? temp : emails).join(', '));
}
FIDDLE
you can detect when an textarea is changed (or other input field) by using an eventhandler. Jquery supports multiple events (have a look here http://api.jquery.com/category/events/). In this particular case I should use the keyup event for triggering the extractEmails function. This way your extraction will be "live". However, it is also possible by catching a blur or change event.
With keyup eventhandler
http://jsfiddle.net/kasperfish/9hLtW/5/
$('#text').on('keyup',function(event) {
emails=extractEmails($(this).val());
$("#emails").text(emails);
});
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
This will convert the entered text to emails when you either lose focus, or enter a comma, as you requested:
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
$("#emailtext").on('keypress blur', function(e) {
if (e.which === 44 || e.type =="blur")
{
$('#emails').text(extractEmails($("#emailtext").val()));
}
});
Here's the fiddle:
http://jsfiddle.net/Mj2KM/

Categories