validating input if starts with "T" or "TP" - javascript

I have an input. I need to validate if the value starts with "T" followed by numbers or "TP" followed by numbers
Accepted values: T12345 or TP12345
My JavaScript code
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase !== 'P' && isNaN(Number(v_second_char))) {
alert('error2');
return false;
} else {
return true;
}
}

function myFunction() {
var ip_value = document.getElementById('test').value; //'AB12345';
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
document.getElementById("error").innerHTML = 'It must be start with T';
} else if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) {
document.getElementById("error").innerHTML = 'error2';
} else {
document.getElementById("error").innerHTML = 'no error';
}
}
It will work on blur <br />
<input type="text" id="test" onblur="myFunction()">
<span id="error">No Error</span>
I think your logic is perfect and should work fine, you just need to change:
v_second_char.toUpperCase
to
v_second_char.toUpperCase()
in last if condition
Final code will be
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) { //change in this line
alert('error2');
return false;
} else {
return true;
}
}
Or for the short line of code you can use the regular expression as shown in above answers.

You can use regular expression to achieve your scenario.
var reg = new RegExp(/^TP?[0-9]+$/)
if((string).match(reg))
return true
else
return false
The condition in the if statement can also be used to retrieve the match string from the original string provided.

Pattern matching against a regular expression would be the best thing to use here. Assuming you are returning true if and only if ip_value is a 'T' or 'TP' followed by at least one number:
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var pattern = new RegExp(/^TP?\d+$/);
return pattern.test(ip_value);
/^TP?\d+$/ is the regular expression pattern or regex for short - if you're not familiar with regexes, a good starting point in the context of Javascript is the MDN Regular Expressions Guide.

Related

Replace (whole word only) that works for all possible keyboard-character combinations in a string?

I am trying to find a non-deprecated method of comparing two strings in Typescript and/or Javascript that can handle any string that can be generated using the special characters available on a standard keyboard, because our application is fetching a randomly generated password from the backend then displaying that in our PASSWORD and CONFIRM PASSWORD fields, instead of fetching the encrypted password from the DB and including it in the response, which could possibly be decrypted with enough effort by someone attempting to crack our password hashing algorithm.
It is comparing the PASSWORD to the CONFIRM PASSWORD and checking if they are equal using the 'eval()' function (because the validation condition is loaded from the DB, and could be "FIELD_1 > FIELD_2", not necessarily always equality checking. It does replacements using .replaceAll() on the condition based on form fields' current form value, then evaluates the conditions using eval(). However, replaceAll requires a regex, and regexes can't have certain special characters unescaped or else an error will occur.)
So, to try to find a solution that works for ALL strings/combinations of characters, I added code at the bottom of my question which will generate random strings and compare them for equality 3000 times, and if there are no issues, it will not print any failure messages. I noticed I can escape MOST strings successfully using the following:
function escapeSpecialCharactersInTestString(str: string) {
str = str.replace(/\$/g, '$$$$');
str = str.replace(/[']/g, "\\'");
return str;
}
However, it is still failing for strings like
\3aeB296Z=DH\D"]Yu[0;MC.dep.UeE8g]&}sz)6N|M?.]q:%/ because of the \3 giving the error Octal escape sequences are not allowed in strict mode. I don't want to have to disable strict mode somehow and shouldn't be required to. However, if I use the deprecated "escape()" function instead, it always works.
function escapeSpecialCharactersInTestString(str: string) {
return escape(str)
}
Looking for a solution that can replace any sequence of characters / any string, and I don't want to worry about using deprecated code.
Code that tests 3000 equal, randomly generated strings for equality and stops if it can't compare them:
const normalCharacters =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const specialCharacters = "#:;#&-?/%+*[]\\_=^!()|{}\",.";
function escapeSpecialCharactersInTestString(str: string) {
// console.log(str)
// WORKS 100% but is deprecated:
// str = escape(str)
str = str.replace(/\$/g, '$$$$');
str = str.replace(/[']/g, "\\'");
return str;
}
function generateRandomString(length: number) {
let characterList = normalCharacters + specialCharacters;
let result = "";
while (length > 0) {
let index = Math.floor(Math.random() * characterList.length);
result += characterList[index];
length--;
}
return result;
}
function evaluateConditionWithTrueOrFalseResult(testString: string) {
let conditionResult = false
let evalResult;
try {
evalResult = eval(testString);
} catch (e) {
console.log(e)
}
if (evalResult == true) {
conditionResult = true
} else if (evalResult == false) {
conditionResult = false
} else {
conditionResult = false
}
return conditionResult
}
function replaceAll(str: any, find: any, replace: any) {
//console.log("str: ",str,", find: ",find,", replace: ",replace)
if(str == null) {
return str;
}
if(find !== undefined && find !== null && find !== '' && find !== true && find !== false && !isDate(find) && isNaN(find)) {
find = escapeSpecialCharactersInTestString(find)
}
if(replace !== undefined && replace !== null && replace !== '' && replace !== true && replace !== false && !isDate(replace) && isNaN(replace)) {
//console.log("escaping special chars: ",replace)
replace = escapeSpecialCharactersInTestString(replace)
//console.log("after: ",replace)
}
// replaces whole word only because of the \\b 's
return str.replace(new RegExp('\\b' + find + '\\b', "g"),replace);
}
function isDate(val: any) {
let isDate = false
if(val !== undefined && val !== null) {
if(typeof val === 'object') {
if(val._isAMomentObject === true) {
isDate = true
}
}
if(Object.prototype.toString.call(val) === '[object Date]') {
isDate = true
}
}
// console.log("is ",val," a date: ",isDate)
return isDate
}
let myOrigString = "'PASSWORD' === 'CONFIRM_PASSWORD'";
for (let i = 0; i < 3000; i++) {
let formValue = generateRandomString(50)
let escapedFormValue = escapeSpecialCharactersInTestString(formValue)
let myReplacedString = replaceAll(myOrigString, 'PASSWORD', escapedFormValue)
myReplacedString = replaceAll(myReplacedString, 'CONFIRM_PASSWORD', escapedFormValue)
if (i > 0 && i % 100 == 0) {
console.log("at iteration: "+i)
}
if (evaluateConditionWithTrueOrFalseResult(myReplacedString) === false) {
console.log(myReplacedString, " failed at iteration: " + i)
break;
}
}

Regular expression begin in javascript

I have an input text where user can write string.
I want to have an regular expression in javascript which check if the string starts with three characters FSM.
If the user write another string which doesn't start with FSM, this string was automatically remove and give the error message
Example:
FSMLERTE True
FSMAMAMA True
SFMABNE false et remove this content in the input
I do this but it's doesn't work
var input22Regex= /^[a-z]$/;
if(inputtxt.value.match(inputRegex)) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
any idea ?
Try the following:
const testRegex = /^FSM/;
function testString(str) {
if (testRegex.test(str)) {
return true;
} else {
console.log("String must start with FSM");
return false;
}
}
console.log(testString('FSMLERTE')); // true
console.log(testString('FSMAMAMA')); //true
console.log(testString('SFMABNE')); // false
You can use startsWith
if(inputtxt.value.startsWith('FSM')) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
}
I think your regex should look like this
/^FSM(.)*/g
You should use /^FSM[A-Z]*/ which will match all inputs that start with FSM and 0 or more capital letters following it. If you want it to be case-insensitive, you can use this instead: /^FSM[A-Z]*/i
var input22Regex = /^FSM[A-Z]*/;
if (inputtxt.value.match(inputRegex)) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
}
You can try this regex
FSM[a-zA-Z0-9]+
Demo

Remove punctuation and spaces from String

The function compress() would accept a sentence and return a string with all the blanks and punctuation removed. This function must call isWhiteSpace() and isPunct().
I've already done the functions to call, but I don't know what's missing from my js code to make it call the functions.
function compress(sent) {
var punc = "; : . , ? ! - '' "" () {}";
var space = " ";
if (punc.test(param)) {
return true
} else {
return false
}
if (space.test(param)) {
return true
} else {
return false
}
isWhiteSpace(x);
isPunct(x);
}
This function must call isWhiteSpace() and isPunct().
So you already have two functions which I assume return true when the passed character is either whitespace or a punctuation mark. Then you need not and should not duplicate this functionality by implementing a duplicate regex based text for whitespace and punctuation in your code. Keep it DRY - don't repeat yourself.
A compress function based on these two functions would look as follows:
function isWhiteSpace(char) {
return " \t\n".includes(char);
}
function isPunct(char) {
return ";:.,?!-'\"(){}".includes(char);
}
function compress(string) {
return string
.split("")
.filter(char => !isWhiteSpace(char) && !isPunct(char))
.join("");
}
console.log(compress("Hi! How are you?"));
I agree that a regex test would probably the to-go choice in a real world scenario:
function compress(string) {
return string.match(/\w/g).join("");
}
However, you specifically asked for a solution which calls isWhiteSpace and isPunct.
You can leverage String.indexOf to design the isPunct function.
function isPunct(x) {
// list of punctuation from the original question above
var punc = ";:.,?!-'\"(){}";
// if `x` is not found in `punc` this `x` is not punctuation
if(punc.indexOf(x) === -1) {
return false;
} else {
return true;
}
}
Solving isWhiteSpace is easier.
function isWhiteSpace(x) {
if(x === ' ') {
return true;
} else {
return false;
}
}
You can put it all together with a loop that checks every character in a string using String.charAt:
function compress(sent) {
// a temp string
var compressed = '';
// check every character in the `sent` string
for(var i = 0; i < sent.length; i++) {
var letter = sent.charAt(i);
// add non punctuation and whitespace characters to `compressed` string
if(isPunct(letter) === false && isWhiteSpace(letter) === false) {
compressed += letter;
}
}
// return the temp string which has no punctuation or whitespace
return compressed;
}
If you return something in a function, execution will stop.
From what I can see, your function doesn't need to return anything... So you should just do this
function compress(sent) {
var punc = ";:.,?!-'\"(){} ";
var array = punc.split("");
for (x = 0; x < array.length; x++) {
sent = sent.replace(array[x], "");
}
isWhiteSpace(x);
isPunct(x);
return sent;
}

Fetching function name and body code from JavaScript file using C#

I need to fetch particular function and its body as a text from the javascript file and print that function as an output using C#. I need to give function name and js file as an input parameter. I tried using regex but couldnt achieved the desired result. Here is the code of regex.
public void getFunction(string jstext, string functionname)
{
Regex regex = new Regex(#"function\s+" + functionname + #"\s*\(.*\)\s*\{");
Match match = regex.Match(jstext);
}
Is there any other way I can do this?
This answer is based on the assumption which you provide in comments, that the C# function needs only to find function declarations, and not any form of function expressions.
As I point out in comments, javascript is too complex to be efficiently expressed in a regular expression. The only way to know you've reached the end of the function is when the brackets all match up, and given that, you still need to take escape characters, comments, and strings into account.
The only way I can think of to achieve this, is to actually iterate through every single character, from the start of your function body, until the brackets match up, and keep track of anything odd that comes along.
Such a solution is never going to be very pretty. I've pieced together an example of how it might work, but knowing how javascript is riddled with little quirks and pitfalls, I am convinced there are many corner cases not considered here. I'm also sure it could be made a bit tidier.
From my first experiments, the following should handle escape characters, multi- and single line comments, strings that are delimited by ", ' or `, and regular expressions (i.e. delimited by /).
This should get you pretty far, although I'm intrigued to see what exceptions people can come up with in comments:
private static string GetFunction(string jstext, string functionname) {
var start = Regex.Match(jstext, #"function\s+" + functionname + #"\s*\([^)]*\)\s*{");
if(!start.Success) {
throw new Exception("Function not found: " + functionname);
}
StringBuilder sb = new StringBuilder(start.Value);
jstext = jstext.Substring(start.Index + start.Value.Length);
var brackets = 1;
var i = 0;
var delimiters = "`/'\"";
string currentDelimiter = null;
var isEscape = false;
var isComment = false;
var isMultilineComment = false;
while(brackets > 0 && i < jstext.Length) {
var c = jstext[i].ToString();
var wasEscape = isEscape;
if(isComment || !isEscape)
{
if(c == #"\") {
// Found escape symbol.
isEscape = true;
} else if(i > 0 && !isComment && (c == "*" || c == "/") && jstext[i-1] == '/') {
// Found start of a comment block
isComment = true;
isMultilineComment = c == "*";
} else if(c == "\n" && isComment && !isMultilineComment) {
// Found termination of singline line comment
isComment = false;
} else if(isMultilineComment && c == "/" && jstext[i-1] == '*') {
// Found termination of multiline comment
isComment = false;
isMultilineComment = false;
} else if(delimiters.Contains(c)) {
// Found a string or regex delimiter
currentDelimiter = (currentDelimiter == c) ? null : currentDelimiter ?? c;
}
// The current symbol doesn't appear to be commented out, escaped or in a string
// If it is a bracket, we should treat it as one
if(currentDelimiter == null && !isComment) {
if(c == "{") {
brackets++;
}
if(c == "}") {
brackets--;
}
}
}
sb.Append(c);
i++;
if(wasEscape) isEscape = false;
}
return sb.ToString();
}
Demo

jQuery validate phone number with with RegEx

I have a simple ajax form and I'm trying to validate that it
has a value
that value is a 10 digit number
I'm trying to use RegEx to do so. Here is what I have so far.
var reg = new RegExp("/[0-9]{10}/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length < 1 && reg.test($("#call_number").val())) {
$("#call_error").show();
return false;
}
});
I know the problem has to do witht he RegExp as if I remove this portion of the code it validates that the box has a value.
EDIT: Here is the final regex I'm using
var regEx = new RegExp("/[0-9]/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length != 10 && !$("#call_number").val().match(regEx)) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
EDIT 2
Using the suggestions here is what i'm usign which allows spaces and dashes that then get stripped on check
$("#call_form").bind("submit", function() {
var Phone = $("#call_number").val().replace(/\D+/g,'');
if (Phone.length != 10) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
Here is what I use - its simple, just posting if someone is searching for the same.
var a = PHONE_FROM_FIELD;
var filter = /^[0-9-+]+$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
Cheers!
Your regex works fine for me... you could shorten it to just /[0-9]{10}/.
Your problem is here:
$("#call_number").val().length < 1. If the number is 10 characters long, it will never be less than 1, no?
You probably meant something like this:
$("#call_number").val().length === 10
No one has said what was wrong with your original effort - it's the slashes (/). When calling RegExp as a constructor, you don't need the slashes (which are a token to indicate a regular expression litteral), e.g.:
var re = /\w+/i;
is equivalent to:
var re = new RegExp('\\w+','i');
Note that you have to quote backslashes for special characters.
One last thing - allow spaces in the number. You might remove them before testing or storing though. Users find it much easier to read numbers in blocks of 3 or 4 digits, e.g.
1234 871 098 is easier to read than 1234871098.
something like this:
var regEx = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
$("#call_form").bind("submit", function() {
var val = $("#call_number").val();
if (!val.match(regEx)) {
$("#call_error").show();
return false;
}
});
function validate_Phone_Number() {
var number = $('field_Id').val();
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(number)) {
return true;
}
else {
return false;
}
}
use same validation with keypress and keyup using jquery , working for me
jquery code
const goodColor = "#0C6";
const badColor = "#FF0000";
const $mobile_validation = $('#mobile_validation');
$('#mobile').on('keyup keypress', function(e) {
if (e.which == 46 || e.which == 45 || e.which < 48 || e.which > 57) {
event.preventDefault();
}
if(this.value.length !=10 ){
$mobile_validation.text("Please enter 10 digit mobile number ");
$mobile_validation.css("color", badColor);
}
if(this.value.length ===10 ){
$mobile_validation.text("Good!");
$mobile_validation.css("color", goodColor);
}
});
html code
<input type="text" id="mobile" class="form-control" name="telephone" maxlength="10">
<span id="mobile_validation"></span>
// check phone number validation
function validatePhoneNumber(number)
{
count=number.length;
if(number[0]!=" " && number[0]!="-" && number[count-1]!=" " && number[count-1]!="-")
{
temp=number.replace(" ", "");
temp=temp.replace("-", "");
if($.isNumeric(temp))
{
if(temp.length>=7 && temp.length<=12)
{
flag=1;
for(i=1;i<count;i++)
{
if(number[i]=="-" || number[i]==" ")
{
if(number[i-1]=="-" || number[i-1]==" " || number[i+1]=="-" || number[i+1]==" ")
{
flag=0;
}
}
}
if(flag==1)
{
valid=1;
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
return valid;
}

Categories

Resources