regular expression in javascript user input - javascript

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
}

Related

How to do a strong validation of password entry and validate confirm password entry

I have some HTML and Javascript that is asks a user to enter a password with the following rules:
At least 8 characters long
At least 1 capital letter
At least 1 lowercase letter
At least 1 special character
At least 1 numeric character
This is followed by a password confirmation entry. There are div blocks below the password and password confirmation inputs that contain error messages enclosed in p tags, that are supposed to becomes visible when any of the errors occur. It doesn't seem to be working.
I am also using C# Razor code in this CSHTML file, so I'm required to use "##" instead of # within strings. If I'm wrong about that though, please let me know.
Password: (Must contain at least 1 lowercase alphabetical character, 1 uppercase alphabetical character, 1 special character, 1 numerica character and at least 8 characters long)
<input type="password" name="password_admin1_create" oninput="return validate_password()"><br><br>
<script>
var password = document.getElementsByName("password_admin1_create")[0];
function validatePassword(val) {
var strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!###\$%\^&\*])(?=.{8,})/;
console.log(re.test(val))
return strongRegex.test(val);
}
function validate_password() {
if (validatePassword(password.value)) {
document.getElementById("password_result_invalid").style.visibility = "hidden";
document.getElementById("password_result_invalid").style.height = "0";
} else {
document.getElementById("password_result_invalid").style.visibility = "visible";
document.getElementById("password_result_invalid").style.height = "initial";
}
}
</script>
<div id="password_result_invalid" class="error_verify">
<p style="color:red">Invalid password format.</p>
</div>
<p>Please confirm the password:</p>
<input type="password" name="password_admin1_create_confirm" oninput="return validate_password_confirm()"><br><br>
<script>
var password_confirm = document.getElementsByName("password_admin1_create_confirm")[0].value;
var password = document.getElementsByName("password_admin1_create")[0].value;
function validate_password_confirm() {
if (password_confirm == password) {
document.getElementById("password_confirmation_invalid").style.visibility = "hidden";
document.getElementById("password_confirmation_invalid").style.height = "0";
} else {
document.getElementById("password_confirmation_invalid").style.visibility = "visible";
document.getElementById("password_confirmation_invalid").style.height = "initial";
}
}
</script>
<div id="password_confirmation_invalid" class="error_verify">
<p style="color:red">Passwords do not match.</p>
</div>
I made this a few weeks ago. Just posting it to see if it can help you (I know it's not the most clean one)
Html
All requirements are shown above and are initially red.
<div class="requirements">
<ul>
<li id="length" class="red">Include at least 8 digits and three special characters</li>
<li id="uppercase" class="red">Include at least one upper case characters (A-Z)</li>
<li id="lowercase" class="red">Include at least one lower case character (a-z)</li>
<li id="numbers" class="red">Include a number (0-9)</li>
<li id="symbols" class="red">Include a symbol (!, #, $, etc.)</li>
</ul>
</div>
JS
Add key up event handler to input fields on current page:
var inputfields = document.forms["changePasswordForm"].getElementsByTagName("input");
for (var i = 0; i < inputfields.length; i++){
inputfields[i].addEventListener('keyup', function(e){
// On every key up, check the password
var password = document.getElementById('sf_guard_user_password');
validatePassword(password.value);
})
}
Then at last my (ugly) validate password function
function validatePassword(password) {
// Minimum 8 characters
if (password.length > 7) {
document.getElementById('length').classList.remove('red');
document.getElementById('length').classList.add('green');
} else {
document.getElementById('length').classList.remove('green');
document.getElementById('length').classList.add('red');
}
// At least one uppercase
if (/[A-Z]/.test(password)) {
document.getElementById('uppercase').classList.remove('red');
document.getElementById('uppercase').classList.add('green');
} else {
document.getElementById('uppercase').classList.remove('green');
document.getElementById('uppercase').classList.add('red');
}
// At least one lowercase
if (/[a-z]/.test(password)) {
document.getElementById('lowercase').classList.remove('red');
document.getElementById('lowercase').classList.add('green');
} else {
document.getElementById('lowercase').classList.remove('green');
document.getElementById('lowercase').classList.add('red');
}
// At least one number
if (/[0-9]/.test(password)) {
document.getElementById('numbers').classList.remove('red');
document.getElementById('numbers').classList.add('green');
} else {
document.getElementById('numbers').classList.remove('green');
document.getElementById('numbers').classList.add('red');
}
// At least one symbol
if (/[$#$!%*#?&]/.test(password)) {
document.getElementById('symbols').classList.remove('red');
document.getElementById('symbols').classList.add('green');
} else {
document.getElementById('symbols').classList.remove('green');
document.getElementById('symbols').classList.add('red');
}
}
At last I'm checking on submit if all requirements are met:
document.getElementById('changePasswordForm').addEventListener('submit', function(e){
e.preventDefault();
// Once again ugly because length is fixed
if (document.getElementsByClassName('green').length > 4) {
document.getElementById('changePasswordForm').submit();
}
})
I don't know if this is going to help you. But I tried :)
You should assign the "pattern" attribute to whatever regex expression fits your password requirements. For example:
< input type="password" id="psw" name="psw"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required >
This link might also help: https://www.w3schools.com/howto/howto_js_password_validation.asp
Use pattern Regex:
At least 8 characters long
At least 1 capital letter
At least 1 lowercase letter
At least 1 special character
At least 1 numeric character
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$"
Usage:
<input type="password" name="pw" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$" title="Strong Password">
My guess is that this expression might work:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[?!%##$%^&*])[A-Za-z0-9?!%##$%^&*]{8,}$
which we would add start and end anchors, and remove some of those escapings.
The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[?!%##$%^&*])[A-Za-z0-9?!%##$%^&*]{8,}$/gm;
const str = `Az0^AAAA
Az0^AAA
Az0^AAAAA`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
The reason you keep seeing Invalid password format. is that you first create a variable:
var password = document.getElementsByName("password_admin1_create")[0];
Then later on, you create it again, setting it directly to the value (which is empty)
var password = document.getElementsByName("password_admin1_create")[0].value;
So the variable password will always stay empty and will never pass the regex check.
Note
Also this variable password_confirm is directly set to empty and in console.log(re.test(val)) there is no re
About the pattern
You could make some minor adjustments to your pattern:
The lookahead (?=.{8,}) Asserts that what is on the right are 8+ times any char, which will also match a space.
You could update that to use a character class to match only the characters that you would allow to match and use an anchor $ to assert the end of the string.
The pattern could make use contrast to assert for example not a digit, and then a digit.
For example:
^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^0-9]*[0-9])(?=[^!##$%^&*]*[!##$%^&*])(?=[!##$%^&*A-Za-z0-9]{8,}$)
Regex demo
Your updated code might look like:
<input type="password" name="password_admin1_create" oninput="validate_password()"><br><br>
<script>
function validatePassword(password) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*])(?=.{8,})/.test(password);
}
var password = document.getElementsByName("password_admin1_create")[0];
function validate_password() {
if (validatePassword(password.value)) {
document.getElementById("password_result_invalid").style.visibility = "hidden";
document.getElementById("password_result_invalid").style.height = "0";
} else {
document.getElementById("password_result_invalid").style.visibility = "visible";
document.getElementById("password_result_invalid").style.height = "initial";
}
}
</script>
<div id="password_result_invalid" class="error_verify">
<p style="color:red">Invalid password format.</p>
</div>
<p>Please confirm the password:</p>
<input type="password" name="password_admin1_create_confirm" oninput="return validate_password_confirm()"><br><br>
<script>
var password_confirm = document.getElementsByName("password_admin1_create_confirm")[0];
var password = document.getElementsByName("password_admin1_create")[0];
function validate_password_confirm() {
if (password.value === password_confirm.value) {
document.getElementById("password_confirmation_invalid").style.visibility = "hidden";
document.getElementById("password_confirmation_invalid").style.height = "0";
} else {
document.getElementById("password_confirmation_invalid").style.visibility = "visible";
document.getElementById("password_confirmation_invalid").style.height = "initial";
}
}
</script>
<div id="password_confirmation_invalid" class="error_verify">
<p style="color:red">Passwords do not match.</p>
</div>

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

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

validating using input.value.match in javascript

I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}

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