"undefined" is appearing for first time during validation on JSP page - javascript

I am validating user input where it should accept only 6 digits or OB followed by 8 digits only.
It works very fine for digits but when I enter any alphabet (other than O) for first time it shows "undefined" in the input text box. How to overcome this? I have initialize all variables and tried changing regular expression(/[OB0-9]*/) also but nothing is working.
Here is my jsp code with RegEx:
<input type="text" value="<c:out value='${bookingPathView.extraAANumber}'/>" name="businessExtrAA" id="enterPassengerDetailsForm.businessExtrAA" size="17" maxlength="10" pattern="[OB0-9]*" class="forceWidth-phone forceWidth6" />
Here is my Javascript code
var keepBusinessExtraMaxLength = function () {
var input = [];
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").each(function(i) {
input[i]=this.defaultValue;
jQuery(this).data("idx",i);
});
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").on("keyup", function (e) {
var field = jQuery(this);
var val=this.value;
var maxLength=isNaN(jQuery(field).val()) ? Number(jQuery(field).attr("maxlength")) : 6;
var thisIndex=jQuery(field).data("idx");
if (this.validity && this.validity.badInput || jQuery(field).is(":invalid") ) {
this.value = input[jQuery(thisIndex)];
return;
}
if (val.length > maxLength) {
val=val.slice(0, maxLength);
jQuery(field).val(val);
}
input[jQuery(thisIndex)]=val;
});
}

Your Regex seems to be matching only the characters , O, B and other numbers...
To make it match
6 digits or OB followed by 8 digits only
You can use this regex: ^(?:[0-9]{6}|OB[0-9]{8})$
Demonstration: http://www.regexpal.com/?fam=96586

Related

regular expression in javascript user input

I am having a problem with regular expression in javascript. What i am trying to do is a form register in which i must validate the first name so i decided to go with javascript validation (can you please tell me if going with js is the better option or going with ajax php reg validation?). So I wrote my code by checking some tutorials and reading from google but i am still having a problem. It is not working ! It runs on blur event using jquery so I need your help please to do this.
The pattern i am trying to check is for special characters in the user input
/[\'^£$%&*()}{##~?><>,|=_+]+$/g;
here is my script:
$(document).on('blur','.first_name_input', function() {
var firstNameInput = $(".first_name_input").val();
if (firstNameInput !== '') {
//var exp = /[a-zA-Z0-9-]+$/g;
var exp = /[\'^£$%&*()}{##~?><>,|=_+]+$/g;
//if (firstNameInput.test(/^[\'^£$%&*()}{##~?><>,|=_+-]+$/)) {
//if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
if (firstNameInput.match(exp)) {
var firstnameValidity = "<div class='name_not_valid_div'>× Not allowed characters present!</div>";
$('body').prepend(firstnameValidity);
$(".name_not_valid_div").hide().fadeIn('slow');
if (!errorArray.includes("firstName")){
errorArray.push("firstName");
}
} else {
$(".name_not_valid_div").hide();
if (errorArray.includes("firstName")){
for(var i = errorArray.length - 1; i >= 0; i--) {
if(errorArray[i] === "firstName") {
errorArray.splice(i, 1);
}
}
}
}
}
});
and my html code is :
<tr>
<td class="label">First Name: </td>
<td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
</tr>
1st: use .trim() to avoid left/right whitespaces or even the spaces without any characters $(".first_name_input").val().trim();
2nd: for validation
// if the string has special characters
function string_has_spec_char(str){
var reg = /[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\?]/g;
return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
var reg = /\s/g;
return reg.test(str);
}
and use it like
if(string_has_spec_char(firstNameInput) === false){
// the first name doesn't have special characters
}
if(string_has_spaces(firstNameInput) === false){
// the first name doesn't have spaces
}

Allow only number after 2 characters (My regex 'eat' the first item, see the code)

I'm creating a validating in my input.
It must allow only numbers and logical operators: 0 to 9 and >, <, >= and <=
Ok. Its already working, but the logical operators only can be typeds in first and second fields, like this:
Input must allow: >=10, >100, <=12123
Input must not allow: >=1212>, >=2<<, >2=>
That is, if the user typed a logical operator in the first and/or second field, he can't typed any logical operator again.
In my code, I check the length of input and if it be bigger than 3 I rewrite the regex, but the first character is 'eated'.
See my code:
$(document).ready(function(){
var txt = $('#txt');
var conteudo = txt.val();
$('#txt').on('input', function (event) {
this.value = this.value.replace(/[^0-9\>\<\=]|^0+(?!$)/g, '');
var qtd = event.target.value;
if(qtd.length > 3){
this.value = this.value.replace(/[^0-9\=]|^0+(?!$)/g, '');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt">
How I can implements it?
Input must allow: >=10, >100, <=12123
Input must not allow: >=1212>, >=2<<, >2=>
---edit-----
Input must allow: >=10, >100, <=12123, 121
Input must not allow: >=1212>, >=2<<, >2=>, 345<3, 2<=3
You could save the last valid value and check the new one and replace it with the last one if not match the condition.
$(document).ready(function(){
var txt = $('#txt');
var last = '';
$('#txt').on('input', function (event) {
if (this.value && !/^([<>]=?)?\d+$/.test(this.value + '0')) { // add zero for checking starting values
this.value = last;
}
last = this.value;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt">

Modifying Javascript for deleting unnecessary characters while inserting a phone number

I use Javascript below to call the Viber messenger chat for a specific phone number I paste into the field. How to change it that when inserting a number, unnecessary characters are removed: spaces, brackets, hyphens and only the last 10 digits of the number are left?
<input type="tel" id="tel" pattern=".{10}" maxlength="10" required />
<input type="button" id="btn-1" value="Viber" onClick="javascript: window.open('viber://chat?number=%2B38' + document.getElementById('tel').value, '_self');" />
Thanks.
You can use basic JS string functions:
(function() { // Do not allow using variables outside script
var tel = document.getElementById("tel");
tel.maxLength = 20; // When JS enabled, limit is more than 10
tel.pattern = ".*"; // When JS enabled, allow everything
tel.onchange = // After input
tel.onkeyup = // Key is up (after character written)
tel.onkeypress = // Character writen (for repeating)
function () {
var str = tel.value;
for (var str_old = null; str !== str_old;) { // Until no changes done
str_old = str;
str = str // You can put here more characters or regex
.replace("-", "") // Multiple similar characters
.replace("–", "")
.replace("—", "")
.replace("/", "")
.replace(" ", "")
.replace("(", "")
.replace(")", "")
.replace("[", "")
.replace("]", "")
.replace("{", "")
.replace("}", "");
}
tel.value = str.substr(-10); // Put it back and use last 10 characters (without '-' means except first 10 characters)
}
})()
<input type="tel" id="tel" maxlength="10" pattern="[^-–—/ ()[\]{}]+" required />
<input type="button" id="btn-1" value="Viber" onClick="javascript: window.open('viber://chat?number=%2B38' + document.getElementById('tel').value, '_self');" />

Insert a dash before the last three characters

I need to be able to add a dash before the last three characters in a text field using either javascript or php. For example, the user enters 1dsb3rs and the input changes to 1dsb-3rs. It doesn't matter if the user sees the change (javascript) or if it happens server-side (PHP) I just need the change to happen.
I have already tried this javascript code, but I can't get it to work:
$("#rid").html(function(i,v){
return v.replace( /^([\w]{4})/, "$1-" );
Here is my textbox code:
<input class="form-control" type="text" id="rid" placeholder="Enter ID" size="15px" maxlength="10" name="rid" required value="<?php echo $rid; ?>">
To do this server-side (assuming data is POST-ed):
if (isset($_POST['rid']))
{
$value = $_POST['rid'];
if (strstr($value, '-') === false)//if no dash is in the $value string
$value = substr($value, 0, -3).'-'.substr($value, -3);//get string minus last 3 chars, add dash, then add last 3 chars
}
Or client-side using JavaScript (using, for example the change event)
document.querySelector('#rid').addEventListener('change', function()
{
if (this.value > 3)
this.value = this.value.replace(/(.{3}$)/, '-$1');
}, false);
This pattern replaces the last 3 chars with a dash, followed by those very same last 3 chars. See the fiddle
String.prototype.splice = function( idx, rem, s ) {
return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};
String.prototype.addDash = function () {
return this.splice( -3, 0, '-' );
};
document.getElementById('myinput').addEventListener('keyup', function (e) {
this.value = this.value.replace(/\-/gi, '');
if (this.value.length >= 4) {
this.value = this.value.addDash();
}
});
Working demo : http://jsfiddle.net/seancannon/2xLFy/2/
You can't use html() method on a form control. You need to use val().
Try:
$("#rid").val(function(i,v){
v.replace( /^([\w]{4})/, "$1-" );
});
jQuery val() API docs
I think this should work for you in javascript.
var addDash = function(str){
var chars = str.split("");
chars.splice(chars.length-3,0,'-');
return chars.join('')
}
call this function with string.
addDash('string');
Output
str-ing

How to extract each character in a textarea using Javascript (not jQuery) Better explained

I have a straight forward classic ASP page that uses a where the user can enter any standard keyboard key plus the Enter key (and even special ALT nnn values if they so desire)
My clarification is that I need to display an accurate character count back to the user on each ONKEYUP. So I need to know if the ENTER key has been pressed (/n) which needs to be counted as 2 chars as well as 8 other chars such as Tilde, Caret Left curly bracket, etc. which also count as 2 characters. Finally I need to validate each ONKEYUP char to ensure that they will be valid SMS chars, if not they need to be replaced in the TextArea with and Underscore (account as 1 char only)
So what I need to do is to be able to validate each character on the ONKEYUP remembering that a char could be inserted anywhere in the TextArea, an existing char could be deleted from the TextArea or parts of or the entire text could be pasted at any time
The current HTML code is as follows:
Enter your message - Characters left
<input type="text" name="chl" value="<%=Cclen%>" size=3 diabled readonly>
<br />
<textarea id="SMSmsg" name="SMSmessage" MAXLENGTH="600" rows=5 cols=35 onKeyUp="textCounter
(this)"></textarea>
<input type="text" name="chl" value="<%=Cclen%>" size=3 diabled readonly>
<br />
<textarea id="SMSmsg" name="SMSmessage" MAXLENGTH="600" rows=5 cols=35 onKeyUp="textCounter
(this)"></textarea>
The JavaScript function testcounter is as follows:
function textCounter() {
var extra = 0;
var nextra = 0;
var msgLength = 160 - (document.gs.SMSmessage.value).length - (document.gs.SMSbot.value).length;
var index = document.gs.SMSmessage.value.indexOf('\n');
while (index != -1) {
extra += 1;
index = document.gs.SMSmessage.value.indexOf('\n', index + 1);
}
Canam = nameCounter()
if (document.gs.SMSrequest.value == 'eml') {
extra = 0
nextra = 0
chnl = 999
} else {
if (document.gs.chnl.value > 0) {
nextra = 3
}
}
document.gs.chl.value = msgLength + extra - nextra;
Camsg = textWarning();
}
function nameCounter() {
var botLength = (document.gs.SMSbot.value).length;
document.gs.chnl.value = botLength;
}
function textWarning() {
var Ccwarn = " ";
if (document.gs.chl.value < -299) {
Ccwarn = "** Error ** - Extended text too long"
} else {
if (document.gs.chl.value < 0) {
if (document.gs.chex.value == 'N') {
Ccwarn = "** Error ** - Standard text too long"
} else {
Ccwarn = "** Warning ** - Extended text - Additional charge applied"
}
}
}
document.gs.chw.value = Ccwarn;
}
Any suggestions as to how to recode the JS function much appreciated taking into account my comments on the user actions within the TextArea

Categories