Replicate C# Server Side Validation in Javascript - javascript

I basically have the following validation on my page - its a word rule in that a description in a text box cannot be greater than 3 words excluding the word 'and'. I have implemented the following server side validation in C# which is working fine
if (Desc.Trim().ToString() != "")
{
MatchCollection collection = Regex.Matches(Desc.Replace("and", ""), #"[\S]+");
if (collection.Count > 3)
{
ErrorMsg.Append("Description should contain at most 3 words(excluding 'and').");
ErrorMsg.Append("\\n");
}
}
However I am having difficulty getting the same working in Javascript. I have tried the following but it isnt working so far so hoping for someone that has a better knowledge of Javascript can see the error. Note the if is part of a bigger validate function that fires on the page - the alerts were just there to see if it got into this if (which it doesnt) - when this is block is removed the rest of the JS on the page is working fine.
if (Desc.val().trim() != "")
{
alert('1');
!regexWordRule.test(Desc.val());
alert('2');
if (Desc.val().match(regexWordRule).length > 3)
{
errorText += "Description should contain at most 3 words(excluding 'and').";
}
valid = false;
}
and the below is my regexWordRule defined at the very top of the js file.
var regexWordRule = /[\S]+/;

You could find a better solution, but this approach came to my mind, so I am posting it:
var input = "and lorem and ipsum";
// remove ands
var deandizedinput = input.replace(/\band\b/g, ' ');
// replace all white spaces with a single space
var normalizedinput = deandizedinput.replace(/\s+/g, ' ');
// split the input and count words
var wordcount = normalizedinput.trim().split(' ').length;
Fiddle here.

In case you are using MVC3, you can use Remote validation on model (RemoteAttribute).
Or you can make such kind of validation manualy with ajax request.
This will keep your code from duplication.

Related

Javascript replace first and last font tag

I'm trying to convert html to bbcode.
My code:
var html = "<font color=\"Green\"><font size=\"4\">test</font></font>"
html = html.replace(/\<font color="(.*?)"\>(.*?)\<\/font\>/ig, "[color=$1]$2[/color]");
Result:
[color=Green]<font size="4">test[/color]</font>
But I need to get another
[color=Green]<font size="4">test</font>[/color]
Please could you correct my mistake. Sorry for my English.
You're going to have difficulty parsing html with regex as you can see from the many many posts on this site about it. Html is not a regular language, and it therefore can be impossible to parse in this way. That being said, if the problem is this simple it should be possible.
Here's a solution that will work in very simple cases to get the first and last part
var html = "<font color=\"Green\"><font size=\"4\">test</font></font>"
,findTag = /<.*?>|([^<]+)/g
,part
,allParts = []
;
while((part = findTag.exec(html)) !== null) {
allParts.push(part[0]);
}
console.log(allParts)
var first = allParts[0]
,last = allParts.slice(-1)[0]
;
console.log(first, last);
You can then parse the first and last as you were doing previously and use array.join() to join everything back.
But again, this will only work in the simple case.
Use negative lookaheads:
html = html.replace(/\<font color="(.*?)"\>(.*?)\<\/font\>(?!\<\/font\>)/ig, "[color=$1]$2[/color]");
To explain what's happening here: The pattern I used is exactly yours, except for an appended (?!\<\/font\>). This so-called negative lookahead basically says: "only make this a match, if I don't encounter </font> next".

javascript validation telephone

I have this function which objective is to validate a phone number introduced by a user with base in 2 regex variables.
if the user has the country Sweden selected and introduces 212341512 the warning shouldnt appear since the phone is valid however that doesnt happen. i still get the warning message to appear even if the phone number matches the conditions in the variable indicators.
function validateTelephone() {
var telephone = document.getElementById('txtTel');
var country=document.getElementById('ddCountry');
var indicators= /^(21|22)\d{7}$/;
if (country.value == "Sweden") {
if (!indicators.test(telephone.value)) {
document.getElementById('lblWarning').style.color = "red";
document.getElementById('lblWarning').innerHTML = 'Invalid Telephone Number';
} else {
document.getElementById('lblWarning').innerHTML = '';
}
} else{
document.getElementById('lblWarning').innerHTML = ' ';
}
}
if you guys have any suggestions about my code or a way to solve this problem i'd appreciate that since im new to this language
I would use libphonenumber, which has a JavaScript library already made for you.
https://code.google.com/p/libphonenumber/
As for your code, the regex is correct, and does match the number provided.
Please try using Chrome's JavaScript debugger. (right-click page, inspect element, sources tab). Put in a breakpoint at the beginning of your function and see what happens. Check the values of variables.

Slip input type value live using javascript

i'm trying to live edit a text box value so that the result will be split every two character,
adding a column and starting from some default character.
what i have till now is this code, that obviously doesn't work:
$('#textboxtext').keyup(function (){
var text = $("#textboxtext").val();
//$(text).attr('maxlength', '12');
var splitted = text.match(/.{2}|.{1,2}/g);
var result = ("B8:27:EB:" + splitted.join(':'));
});
i need the live split and the default character inside the textbox but i really don't know where to start...
From your code, it seems like you're trying to create a text box that has some very specific behavior. It looks like it needs to format its value in such a way that it always begins with certain 'prefix' of B8:27:EB:, and every subsequent pair of characters is is separated by a :. This is actually a very complex behavior and you have to consider a number of different interactions (e.g. what happens when the user attempts to delete or modify the prefix). I usually try to avoid such complex controls if possible, however here is a quick implementation:
$('#textboxtext').keyup(function (e){
var prefix = "B8:27:EB:",
text = $(this).val(),
splitted, result;
if (text.indexOf(prefix) == 0)
text = text.substr(9);
else if (prefix.indexOf(text) == 0)
text = "";
text = text.replace(/:/g, '');
splitted = text.match(/.{1,2}/g) || [];
result = prefix + splitted.join(':');
$(this).val(result);
});
Demonstration
Type inside the text box and see what happens. Also note, there are all kinds of interaction that this implementation doesn't account for (e.g. right-clicking and pasting into the text box), but it's a start.

Typewriter-Effect for HTML with JavaScript [duplicate]

This question already has answers here:
Converting a recursive function into an asynchronous CPS implementation (javascript)
(3 answers)
Closed 8 years ago.
I want to do the following: I want to have a typewriter effect in HTML/JavaScript (jQuery/jQuery UI, if needed). There are tons of great examples out there on how to create a typewriter effect on a string (for example this one). I want to do something similar, but with a complete HTML string, which shouldn't be typed out, but inserted properly into the web page.
Example string:
<p>This is my <span style='color:red;'>special string</span> with an <img src="test.png"/> image !</p>
This string should be typed with a typewriter animation. The color of "special string" should be red, even while typing, and the image should appear after the word "an" and before the word "image". The problem with the solutions out there is that they insert the markup character by character into the web page, which results in an unclosed while typing the "special string" in this example. I considered parsing the string with jQuery and iterating over the array, but I have no idea how I would deal with nested tags (like p and span in this example)
I think you don't really need a plugin to do this stuff, I made a simple example:
html:
<div id="typewriter"></div>
js:
var str = "<p>This is my <span style='color:red;'>special string</span> with an <img src='http://placehold.it/150x150'> image !</p>",
i = 0,
isTag,
text;
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('typewriter').innerHTML = text;
var char = text.slice(-1);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(type, 80);
}());
And here is the demo on jsfiddle
There is a fantastic plugin available on Github, here. An example from the README looks like this:
It's nice and configurable depending on how human-like you want the output to be. A simple example looks like this:
var tw = typewriter($('.whatever')[0]).withAccuracy(90)
.withMinimumSpeed(5)
.withMaximumSpeed(10)
.build();
I will forward you to my old website design which used it.
myWebsiteImplementsThis
It makes use of jTypeWriter.js, blink.js, and jquery.
In the source you will the code.
You would want to take a look at function start()
and that will start the login design. I actually put it on hiatus, because there are actually some minor issues IRL i am working on, but you can easily see a working example at least :)
code:
$(function(){
start();
});
function start(){
$("#start").show();
setTimeout(ssh,1000);
}
function ssh(){
$("#ssh").show().jTypeWriter({duration:2.5});
setTimeout(pass,3000);
}
function pass(){
$("#pass").show();
setTimeout(...,2500);
}
/* etc etc */
Markup:
<pre id="start" style="display:none;">localhost$ <span id="ssh" style="display:none;">ssh fallenreaper#www.fallerneaper.com</span></pre>

Javascript not working in firefox

I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";

Categories