JavaScript using regex for validation - javascript

I am validating a form and the text put into a form must be CIT, BIS or MATH
if(dept == ""){
msg += "You must enter a department\n";
}else if((dept != "CIT") && (dept != "BIS") && (dept != "MATH")){
msg += '"' + dept + '"' + " is not one of CIT, BIS, or MATH.\n";
}
I need to add some form of regex to make sure that the text CIT, BIS or MATH when input can be put in any form uppercase and lowercase.
Any help would be great
Thanks

There's no need for a regex.
Just convert your input to lowercase before validating it.
if (dept == "") {
msg += "You must enter a department\n";
}
else if (isInvalid(dept)) {
msg += '"' + dept + '"' + " is not one of CIT, BIS, or MATH.\n";
}
function isInvalid(u) {
var s = u.toLowerCase();
var validStrings = [ "cit", "bis", "math" ];
for (var i = 0; i < validStrings.length; i++) {
if (s === validStrings[i]) {
return false;
}
}
return true;
}
As #y_nk has pointed out, the following approach would be more efficient (if necessary):
function isValid(s) {
var validationObject = { "cit" : true, "bis": true, "math": true };
return validationObject[ s.toLowerCase() ] === true;
}

If you really think regular expressions are the way:
if (!/^(?:BIS|CIT|MATH)$/i.test(dept)) {
}
The expression had to be anchored, which is why you also see the non-capturing group in there.
A nicer approach is this:
if (['cit', 'bis', 'math'].indexOf(dept.toLowerCase()) == -1) {
}
Unfortunately, that only works from IE9 onwards due to Array.indexOf()

Something like this
var regex = new RegExp("^CIT$|^BIS$|^MATH$", "i");
if(dept == ""){
msg += "You must enter a department\n";
}else if(!regex.test(dept)){
msg += '"' + dept + '"' + " is not one of CIT, BIS, or MATH.\n";
}

Related

Parse line by line, then word by word from a textarea in jquery

I'm creating a basic .fountain editor to html parser that pretty much checks for words typed in a textarea on keyup.
Line by line parsing works below, but of course users would type in " **bold** then *italic* " in a single line but I can't seem to get it to scan each word in a line.
Below is my code:
jQuery.fn.parseAsFountain = function( window, jQuery ){
jQuery = $;
var storybox = $(this).val();
story = storybox.split('\n');
// Process The entire box
for( var i=0;i<story.length;i++ ){
var line = story[i];
SubstitutePerLine(line);
}
story_cleared = story.join('\n');
story_breaks = story_cleared.replace(/(?:\r\n|\r|\n)/g, '<br />');
return story_breaks;
function SubstitutePerLine(line){
if( line.match(/^[*].*[*]$/) ){
newval = line.slice(1, -1);
if( newval.match(/^[*].*[*]$/) ){
newval2 = newval.slice(1, -1);
if( newval2.match(/^[*].*[*]$/) ){
newval3 = newval2.slice(1, -1);
if( newval3.match(/\\/) ) {
if(newval3.match(/\\\*/)){
slash_val = newval3.replace(/\\/, '');
story[i] = '<b><i>' + slash_val + '</i></b>';
}
else {
story[i] = '<b><i>' + newval3 + '</i></b>';
}
}
else {
story[i] = '<b><i>' + newval3 + '</i></b>';
}
}
else if( newval2.match(/\\/) ) {
if(newval2.match(/\\\*/)){
slash_val = newval2.replace(/\\/, '');
story[i] = '<b>' + slash_val + '</b>';
}
else {
story[i] = '<b>' + newval2 + '</b>';
}
}
else {
story[i] = '<b>' + newval2 + '</b>';
}
}
else if( newval.match(/\\/) ) {
if(newval.match(/\\\*/)){
slash_val = newval.replace(/\\/, '');
story[i] = '<i>' + slash_val + '</i>';
}
else {
story[i] = '<i>' + newval + '</i>';
}
}
else {
story[i] = '<i>' + newval + '</i>';
}
}
if( line.match(/#/) ){
newval = line.replace(/^#/, '');
story[i] = '<p hidden>' + newval + '</p>';
}
if( line.match(/##/) ){
newval = line.replace(/^##/, '');
story[i] = '<p hidden>' + newval + '</p>';
}
if( line.match(/###/) ){
newval = line.replace(/^###/, '');
story[i] = '<p hidden>' + newval + '</p>';
}
return story;
}
}
I've tried re-splitting it by word in another split(" ") inside the loop then joining it again afterwards but to no avail.
Parsing markup is not a straightforward task. To name a few things:
If an asterisk is followed by a space, it will not be the start of a formatted piece of text;
Several parts can be formatted in one line, not only single words, but also word groups;
Formatting may even cross over a line break.
There might be an even number of slashes preceding an asterisk, in which case the asterisk is not escaped.
Here is a solution that only deals with italic, bold and italic+bold formatting, and the removal of escaping slashes. I did not deal with the hashes (#) as this was already quite broad for a Q&A:
jQuery.fn.parseAsFountain = function() {
var txt = this.val(),
re = /(\s?)(\\*)(\*+)(?=(\s?))/g,
arr,
openAsterisks = 0,
result = [],
last = 0,
start;
while ((arr = re.exec(txt)) !== null) {
var [all, prefix, escaped, asterisks, suffix] = arr;
if (escaped.length % 2) { // First asterisk is escaped
escaped += asterisks[0];
asterisks = asterisks.substr(1);
if (!asterisks.length) continue; // Nothing to do
}
var useAsterisks = 0;
if (openAsterisks && !prefix.length) {
useAsterisks = Math.min(openAsterisks, asterisks.length);
// Add HTML for bold, italic or both
result.push(
txt.substr(last, start - useAsterisks - last),
['<i>','<b>','<i><b>'][useAsterisks-1],
txt.substr(start, arr.index + escaped.length - start),
['</i>','</b>','</b></i>'][useAsterisks-1]);
last = arr.index + escaped.length + useAsterisks;
openAsterisks = 0;
}
if (!openAsterisks && asterisks.length > useAsterisks && !suffix.length) {
openAsterisks = asterisks.length - useAsterisks;
start = arr.index + prefix.length + escaped.length + asterisks.length;
}
}
// Flush remaining text
result.push(txt.substr(last));
// Remove escaping slashes (not escaped ones!):
result = result.join('').replace(/\\(.)/g, '$1');
return result;
}
$('textarea').on('input', function () {
$('pre').html($(this).parseAsFountain());
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea style="width:100%" rows=5>
This is **a** test *with several* ***formats
but*** keeping asterisks \*where* needed.
</textarea>
<h3>Rendered:</h3>
<pre>
</pre>

I want to get the numbered list like in MS Word

This is the code I have written -
$('#comment_content').keypress(function(key) {
if (key.which == 13) {
if(matched = content.match(/\n\d\./g)) {
console.log(matched);
$('#comment_content').val(content + "\n" + ++matched + ".")
key.preventDefault();
}
}
});
'#comment_content' is the id of the textarea.
I want something like in MS word
Some Text (press Enter key)
(new line)2. Some text
(new line)3.
I'm unable to get the result need help.
Your regex is an issue - the content won't start with a newline character, it'll start with number and a dot:
$('#comment_content').keypress(function(key) {
var content = $('#comment_content').val();
if (key.which == 13) {
if(matched = content.match(/^\d\./)) {
console.log("matched numbered list start!: "+ matched);
$('#comment_content').val(content + "\n" + ++ matched + ".")
key.preventDefault();
}
}
});
jsfiddle

Custom Valid URL validation using regular expression in Javascript

Here,
I am validating URL with following string which either it should be http/https or ip address along with query string and different parenthesis square bracket [] .
I want to prevent following url parenthesis
2)http://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]Id] - Not Allowed
what should be regular expression to prevent [publisher[client_id]Id] sting ?
I'm using following regular expression for above strings
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(str)) {
return false;
} else {
return true;
}
what should be changed code for same?
Please help me for the same.
Try this:
var strings = [
'[publisher[client_id]Id]',
'[publisher_id]'
];
var pattern = /\[.*\[.*\].*\]/;
strings.forEach(function(string){
if(pattern.test(string)) {
console.log(string + " -> matched");
}
else {
console.log(string + " -> not matched");
}
});
try this. the first group return url without parameter (withour your publiser, etc)
sorry didn't read it carefully. try that one and return true if valid
edited
var t1 = "htts:/192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]";
var t2 = "https://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192";
var t3 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]";
var t4 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?name=[publisher[client_id]]";
var t5 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?foo=bar&name=[publisher[client_id]]";
function check(str) {
var url = /((http[s]?:\/\/){1,1}(\w+[-.\/]{0,1}\w?)*)/g,
p = /([\?\&](\w+=){0,1}\[\w+\[\w+\]\w*\])/g;
/*check for url*/
if (!url.test(str)) {
return "invalid url";
}
/*check for [userid[userid]]*/
return p.test(str) ? "invalid" : "valid";
}
document.body.innerHTML = check(t1) + "</br>";
document.body.innerHTML += check(t2) + "</br>";
document.body.innerHTML += check(t3) + "</br>";
document.body.innerHTML += check(t4) + "</br>";
document.body.innerHTML += check(t5) + "</br>";
regards

Is there a cleaner solution for this conditional statement? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is there a cleaner, more concise way to write the following conditional statement that creates a string in Javascript?
var search;
if (text === '' && user === '' && filter !== '') {
search = filter;
} else if (filter === '' && text === '' && user !== '') {
search = 'email="' + user + '"';
} else if (filter === '' && user === '' && text !== '') {
search = 'text~"' + text + '"';
} else if (text !== '' && user !== '' && filter === '') {
search = 'text~"' + text + '" ANDemail="' + user + '"';
} else if (text !== '' && filter !== '' && user === '') {
search = 'text~"' + text + '" AND ' + filter;
} else {
search = 'text~"' + text + '" AND ' + filter + '" ANDemail="' + user + '"';
}
// using computed switch
var TEXT = 1, haveText = (text !== "") << 0;
var FILTER = 2, haveFilter = (filter !== "") << 1;
var USER = 4, haveUser = (user !== "") << 2;
switch(haveText + haveFilter + haveUser)
{
case FILTER: search = filter; break;
case USER: search = 'email="' + user + '"'; break;
case TEXT: search = 'text~"' + text + '"'; break;
case TEXT+USER: search = 'text~"' + text + '" AND email="' + user + '"'; break;
case TEXT+FILTER: search = 'text~"' + text + '" AND ' + filter; break;
case TEXT+FILTER+USER: search = 'text~"' + text + '" AND ' + filter + '" AND email="' + user + '"'; break;
case FILTER+USER: search = filter + '" AND email="' + user + '"'; break;
default: search = ""; // no search criteria
}
makes two possible errors in the compound if statement version stand out:
The case of FILTER+USER was not tested for and produced a search using TEXT,
The case of no criteria was not tested in the if statement and also produced a search using TEXT.
Off the top of my head, one thing you can do to simplify this is to use the js rule that '' falsy which simplifies this. Also, short circuits with return would help.
var search;
function getSearch(user, text, filter) {
if (!text && !user && filter) return filter;
if (!filter && !text && user) return 'email="' + user + '"';
if (!filter && !user && text ) return 'text~"' + text + '"';
if (text && user && !filter) return 'text~"' + text + '" ANDemail="' + user + '"';
if (text && filter && !user) return 'text~"' + text + '" AND ' + filter;
return 'text~"' + text + '" AND ' + filter + '" ANDemail="' + user + '"';
}
search = getSearch(user, text, filter);
I think that's a little cleaner. It could be cleaned up a lot if the formatting of your string wasn't so strange, but I'm assuming it's specific and required so this maintains the exact formatting you're after in the "search" string.
You can make a function to build the search string, that way you can easily add more variables in the future. The builder is messy, it's a messy process, but it won't get much more messy, no matter how many variables you add. As a side-note, remember that in some cases like this (with a lot of conditionals) you can consider refactoring using polymorphism, that probably wouldn't work for you here, though. The fiddle for this is here: https://jsfiddle.net/ytg1rxu8/
function buildSearchString(text, user, filter) {
var returnString = '';
var strings = [];
if (text) {strings.push('text~ =' + text);}
if (user) {strings.push('email = ' + user);}
if(filter){
strings.push(filter);}
var length = strings.length;
for(var i =0; i < length; ++i){
var s = strings[i];
if(i ===length -1){
returnString += s;
}
else{
returnString += s+' AND ' ;
}
}
return returnString;
}
alert(buildSearchString('', 'there', 'guy'));
The following may fit the criterion "concise", but it may not fit "cleaner":
var text = 'someText';
var filter = '';
var user = 'aUser';
var search = text? 'text~"' + text + '"' : '';
search += search && filter? ' AND ' + filter : filter? filter : '';
search += search && user? ' AND email="' + user + '"' : user? 'email="' + user + '"' : '';
document.write('Search: ' + search); // text~"someText" AND email="aUser"
var search;
if (filter)
search = appendFilter(search, filter);
if (text)
search = appendFilter(search, 'text~"' + text + '"');
if (user)
search = appendFilter(search, 'email="' + user + '"');
function appendFilter(search, f) {
return search ? search + ' AND ' + f : f;
}

Why doesn't this function give window.alert when user enters spaces or too many/not enough characthers?

Seemed like an easy problem to solve. Cannot figure out why the code will return the secret word despite entering spaces or too many/too few characters. Need a little help. Thanx!
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
<!--variable to hold secret word-->
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
do {
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length < 6) {
window.alert("secret word is too short");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length > 6) {
window.alert("secret word is too long")
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user_prompt.indexOf('') >= 0) {
window.alert("secret word cannot contain spaces");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
}
while(user_prompt != -999);
}
Apart from the typos you have (user_prompt != user.prompt), you're looking for a 7-character string with no spaces.
What this condition checks:
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
is a 6-character string with ANY character present.
What you need instead is:
if(user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
This will be true if the string length is 7 and there are no spaces.
Here's a working example, I've simplified it a bit so it's easier to work with in a snippet here, but you can see and reuse the conditions:
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
document.getElementById("guess").innerHTML = '';
if (user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
document.getElementById("guess").innerHTML = text + "<br>" + user_prompt + "<br>" + output;
} else if (user_prompt.length < 7) {
document.getElementById("guess").innerHTML = "secret word is too short";
} else if (user_prompt.length > 7) {
document.getElementById("guess").innerHTML = "secret word is too long";
} else if (user_prompt.indexOf(' ') >= 0) {
document.getElementById("guess").innerHTML = "secret word cannot contain spaces";
}
}
<div id="guess"></div>
<button onclick="secretWord()">Run</button>
else if(user.prompt.length < 6) {
// ...
else if(user.prompt.length > 6) {
In both cases, user.prompt.length should be user_prompt.length
your problem is in else if statement
it should be user_prompt and not user.prompt
besides, even if you enter space yet exactly right amount of characters say 6 or so, it will pass the first if test.
you are not checking for space i.e. ' ' but ''. see to it you check for spaces properly.

Categories

Resources