Jquery Postal code clientvalidate - javascript

I am working on a customvalidator to validate and replace (if possible) a postal code.
This is a Dutch postal code and should look like "5050 AA". When the user enters "5050AA" this postal code should be replaced with "5050 AA". I tried this by adding the following script to my page, which is called in the customvalidator:
<script type="text/javascript">
function Postcode_ClientValidate(source, arguments) {
var val = arguments.Value
var result = "";
var myPCRegExp1 = new RegExp("^[1-9][0-9]{3}\s?[a-zA-Z]{2}$", "i");
var myPCRegExp2 = new RegExp("(\d{4}) (\w{2})");
if ((!myPCRegExp1.test(val)) && (!myPCRegExp2.test(val))) {
arguments.IsValid = false;
} else {
if (myPCRegExp1.test(val)) {
arguments.Value = val.replace(myPCRegExp1, "$1, $2");
arguments.IsValid = true;
} else if (myPCRegExp1.test(val)) {
arguments.IsValid = true;
}
}
//jQuery("input#[HIERDEID]").val("Test");
}
</script>
However, the script above is picking up the "5038AA" but not the "5038 AA" as a match, so i can't validate a working postal code and can't rewrite to the valid postal code.
What am I doing wrong?
It's a standard .aspx page with a form and a customvalidator:

Try battling it out with this tool:
http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx for testing this sort of thing.

"5038 AA" is matching myPCRegExp1, too, because of the '\s?'
I think you need this:
var myPCRegExp1 = new RegExp("^([1-9][0-9]{3})([a-zA-Z]{2})$", "i");

Related

Reusing Javascript code without repasting it again and again

I have the below code, which looks for the text "UID" and changes it to "UID *"
On my page, there are other terms such as "description", "score" and so on. I would also like to append * to these as well - is there a tidy way to get the below code to edit those as well? Only way I know is to repeat this code block again and again?
<script type="text/javascript">
//Mark UID as Mandatory
var CFN = "UID";
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(CFN, 'UID *'));
});
}
</script>
EDIT. I tried the below reply, but this didn't work for me, I have got this code now, but again, doesn't seem to work (its trying to add a * onto "UID" and "Description" where found using a multi variable;
<script type="text/javascript">
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.append(MandatoryCFs, ' *'));
});
}
</script>
Replace multiple strings by using list of| Regex
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(new RegExp(MandatoryCFs.join('|'),'g'), '$& *'));
});
}
or like this if you don't need to the replaced strings to be dynamic:
text.replace(/UID|Description/g, '$& *')

.val() not assigning return to new variable

After this zip will remain at 0 no matter what the value of "input" is. I suspect it has something to do with apiAddress not updating zip after the new value is assigned to zip. Can any one explain what is happening?
$(document).ready(function() {
zip = 0;
apiAddress = "api.openweathermap.org/data/2.5/weather?zip=" + zip;
$("#submit").on("click", function() {
zip = $("input").val();
$("#temperature").html(apiAddress);
});
});
You are adding the zip variable to your url in the wrong place. Also, it's better to care about variable scope. Try this:
$(document).ready(function() {
var zip = 0;
$("#submit").on("click", function() {
zip = $("input").val();
apiAddress = "api.openweathermap.org/data/2.5/weather?zip=" + zip;
$("#temperature").html(apiAddress);
});
});
First of all it's good practice to use console.log() to see what is being returned by $("input").val();. Add the following line to your code and check your browser's console to see the value being logged after submiting:
$(document).ready(function() {
zip = 0;
$("#submit").on("click", function() {
console.log( $("input").val() ); //Add this line
zip = $("input").val();
apiAddress = "api.openweathermap.org/data/2.5/weather?zip=" + zip;
$("#temperature").html(apiAddress);
});
});
There might be more than one <input> tag in your html. Try giving it an id like <input id="inp1"> and change your javascript code to:
zip = $("#inp1").val();

Extract email addresses from a text file using JavaScript

I have more than 2000 email addresses. which i have exported from feedburner.
And the email address look like below;
adminvicky#gmail.com Active 12/05/2015 03:07
adminvishal250#gmail.com Pending Verification 8/05/2015 01:07
I want to extract email address from the text file by removing Active, Pending Verification, Date [i.e. 8/05/2015] and time [i.e 03:07] using JavaScript.
I have created a JavaScript Program which something like below which working properly for removing Active, Pending verification text,
<script>
function extracter() {
var a = document.getElementById('input').value;
document.getElementById('output').innerHTML =
a.replace(/Active|Pending|Verification| /g, '');
}
</script>
<textarea id="input"></textarea><br/>
<br/>
<input type="button" value="click" onclick="extracter()"/>
<br/>
<br/>
<textarea id="output"></textarea>
And the output is,
adminvicky#gmail.com 12/05/2015 03:07
adminvishal250#gmail.com 8/05/2015 01:07
And I want the below output. Just help me to remove "Date" and "Time",
adminvicky#gmail.com
adminvishal250#gmail.com
Try this one, i think it will do the job
var a = document.getElementById('input').value;
document.getElementById('output').innerHTML = extractEmails(a).join('\n');
And the function:
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
Here is a fiddle
Here is also an example using jQuery also Extract all email addresses from bulk text using jquery
Try to use this regex:
([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)
REGEX DEMO
In your Javascript you can implement it like this:
function getMail ( text ){
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
JSFIDDLE DEMO
you can easily write a regex and iterate over the results like:
var reg = new RegExp(/^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/g);
var email;
while((email = reg.exec(targetText)) !== null) {
// do something with the email
}
Let's try with this simple regular expression:
var record = ' adminvicky#gmail.com Active 12/05/2015 03:07';
var regExp = /^\s*(.*?)\s+/;
console.log(record.match(regExp)[1]);
You can try this regex instead:
a.replace(/\s+.+$/g, '')
This should work for your case.
I would use string.split(" ") and split the textfile at its spaces.
Example:
var string = " adminvicky#gmail.com Active 12/05/2015 03:07 adminvishal250#gmail.com Pending Verification 8/05/2015 01:07"
var array = string.split(" ");
var emails = [];
for(var i = 0; i < array.length; i++){
if(array[i].indexOf("#") != -1){
emails.push(array[i]);
}
};
Then you have an array emails which contains your email adresses.
Using JQuery load function to read content from .txt file and display email as hyperlink:
$(document).ready(function(){
//Get the text content from txt file using load function
$( "#divid" ).load( "/xyz.txt",function(response, status, xhr){
if(status=='success') {
/* After loading the static text, modifying the email address to hyper link */
var corrected = response;
var emailRegex =/[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/g;
corrected.match(emailRegex).forEach(function(email) {
console.log(email);
corrected = corrected.replace ( email, '' + email + '' );
});
$('#divid').html(corrected);
}
});
});

how to remove everything except numeric 1234567890 using javascript

i have the following javascript how and where to set so when it will get the data and shows in a textbox it will show only numeric values:
<script type="text/javascript">
function showData($sel){
var str='';
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
str+=(str!='') ? ', '+sel.options[i].value : sel.options[i].value;
}
}
sel.form.selectedFruits.value = str;
}
</script>
i have multiple select dropdown and it has multiple values like Staff No and email so i dont want to show email in text box only staff no and even i dont want to remove email from values.
it is working fine except what i want to do :D
A simple solution, if you want to get only numbers from a string (or html in your example), will be :
var str= document.getElementById(id).innerHTML;
return str.replace(/[^0-9]/ig, '');
See this jsfiddle.
if I've gotten the point correctly try something like this
<script type="text/javascript">
function showData($sel){
var str=[];
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
str[i]+=sel.options[i].value.replace(/\D/g, ''); // remove everything except digits
}
}
sel.form.selectedFruits.value = str.join();
}
</script>
<script type="text/javascript">
function showStaffno(sel){
var str='';
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
if (sel.options[i].selected){
str+=(str!='') ? ', '+sel.options[i].value.replace(/\D/g, '') : sel.options[i].value.replace(/\D/g, '');
}
}
sel.form.selectedFruits.value = str;
}
</script>

Validation Output -> Picking up javascript

Why is my code picking up the following error?
Line 32, Column 14: character "<" is the first character of a delimiter but occurred as data
for(i=0; i <= length; i++) {
This message may appear in several cases:
You tried to include the "<" character in your page: you should escape it as "<"
You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&", which is always safe.
Another possibility is that you forgot to close quotes in a previous tag.
Line 32, Column 14: StartTag: invalid element name
for(i=0; i <= length; i++) {
Code:
<script type="javascript">
function randomRange(minVal,maxVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return (Math.floor(randVal));
}
function GetCaptcha() {
var encStr = "123456789ABCDEFGHJKMNPQRSTUVWXYZ";
var length = randomRange(4,8);
var result = "";
var i = "";
var char = "";
for(i=0; i <= length; i++) {
char = encStr.substr(randomRange(1,encStr.length),1);
result += char;
}
return result;
}
function InitCaptcha() {
var hidFld = document.MyForm.captchaHidFld;
str = GetCaptcha();
hidFld.value = str;
document.getElementById('captchaTxt').innerHTML = str;
document.getElementById('captchaBtn').value = str;
}
function ValidateCaptcha (theForm) {
var inpStr = (document.MyForm.captchaInpFld.value).toUpperCase();
var captStr = document.MyForm.captchaHidFld.value;
if (inpStr.length == captStr.length)
{
if (inpStr.match(captStr)) { return true; }
}
return false;
}
function cmdSubmit(theForm)
{
if (!ValidateCaptcha(theForm))
{
alert ("Please enter valid CAPTCHA Code.");
return false;
}
if (theForm.name.value == "")
{
alert ("Please enter your name.");
theForm.name.focus();
return false;
}
if (theForm.email.value == "")
{
alert ("Please enter your e-mail address.");
theForm.email.focus();
return false;
}
return true;
}
</script>
With that transitional XHTML DOCTYPE you'll need to enclose inline Javascript and CSS like this:
<script type="text/javascript">
//<![CDATA[
/* script here */
//]]>
</script>
Compare these results:
this is invalid
this validates
What are you using to validate this? You could always include the javascript as an external javascript file to get around this?
Also: Make sure the script tag is inside a <head> or <body> element?
Your code looks correct. If you bebug the code partially, i.e. GetCaptcha() using firebug, you will be able to track the error quickly.
or Post the HTML related to this code :)

Categories