How to validate postcode in a form using JavaScript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to validate a postcode using JavaScript.
I have my regex.
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$
This is my function so far, not sure how to implement regex.
function validatePostcode()
{
var postcode = document.getElementById("postcode").value;
}
Any other suggestions that would format a postcode that matches;
CF24 9DG

You can do something like this:
function validatePostalCode(){
var regExp = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$/;
var postcode = document.getElementById("postcode").value;
if( regExp.test( postcode ) ){
// Do something here, result is true.
} else {
alert("result is false");
}
}
You can try it out in this fiddle: http://jsfiddle.net/Cedriking/5b8wtf1f/2/

You should use JavaScript test() Method RegExpObject.test(string) that returns:
TRUE if the input string matches the RegExpObject regex
FALSE if the input string does not match the RegExpObject regex
Your validator function should look like this:
var validatePostCode = function(postCode) {
var parsePostCode = 'your_regex';
return parsePostCode.test(postCode);
};
var postCode = document.getElementById("postcode").value;
validatePostCode(postCode); // calling the validator function

Related

replace the string from just before the last dot(.) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a string like A/B/C/D.txt
So I want to replace the character just before the last . with the new one.
Like I would add E in last So the output should be A/B/C/E.txt
Can this is possible with only replace and concat Or Regex should help?
I'm sure the output is correct.
A/B/C/E.txt
var filename = 'A/B/C/D.txt';
var dotIndex = filename.lastIndexOf('.');
document.write(filename.substr(0, dotIndex-1) + 'E'+filename.substr(dotIndex, filename.length-dotIndex));
var parts = 'A/B/C/D.txt'.split('.');
if(parts.length > 1)
{
parts[parts.length-2] = parts[parts.length-2].replace(/.$/,"E");
let result = parts.join('.');
console.log(result);
}
Try this:
let name = "A/B/C/D.txt"
let res = name.substr(0, name.lastIndexOf(".")) + "E." + name.substr(name.lastIndexOf(".") + 1);
console.log(res);

How to format input value on keyDown()? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I would like to force the input value of a text field to comply with a specific format. It needs to be capitalized and with no numbers allowed.
I would like this event to fire on onKeydown().
Examples:
Lionel MESSI => Lionel Messi
LiONEL MesSI => Lionel Messi
Neymar JR => Neymar Jr
Neymar 22 JR => Neymar Jr
Franck D'HONNEUR => Franck D'Honneur
Kevin PEREZ ROBERTO => Kevin Perez Roberto
There is no simple one-liner way of doing this. However, you can make a function which can format the name for you.
Originally taken from this answer, I've modified it slightly to reflect your desired output:
var name1 = "Lionel MESSI";
var name2 = "LiONEL MesSI";
var name3 = "Neymar JR";
var name4 = "Neymar 22 JR";
var name5 = "Franck D'HONNEUR";
var name6 = "Kevin PEREZ ROBERTO";
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/[0-9]/g, '');
}
console.log(toTitleCase(name1));
console.log(toTitleCase(name2));
console.log(toTitleCase(name3));
console.log(toTitleCase(name4));
console.log(toTitleCase(name5));
console.log(toTitleCase(name6));
You may want to check out toUpperCase() and toLowerCase() from the MDN documentation.
To get this functionality in on onKeyDown(), you can use jQuery like the snippet below. I do advice against onKeyDown() though as this creates a weird user experience. Try onBlur instead.
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/[0-9]/g, '');
}
$("#name").on("keydown", function() {
$(this).val(toTitleCase($(this).val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Name: <input id="name">
With the help of a little helper function from this question: How do I make the first letter of a string uppercase in JavaScript?
I wrote a quick script that fires on input blur:
$(document).ready(function() {
function capitalizeFirstLetterOfEachWord(string) {
strArr = string.split(' ');
resArr = [];
for(i=0;i<strArr.length;i++){
resArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1);
}
return resArr.join(" ");
}
$('.forceCapital').blur(function(e) {
$(this).val(capitalizeFirstLetterOfEachWord($(this).val()));
});
});
https://jsfiddle.net/sa2ox30d/2/

I can't replace this pattern in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need your help on my new project
I hate regular expressions and its rules but i must use it this project.
want do this replace
var aString = '[bkz:sample key]';
I want get into key variable 'sample key' value from this aString
var key,clean;
key = 'sample key';
clean = cleanChars(key);
// clean = sample_key
//my target
key
how can i do this?
thanks in advance
function extractKey(str) {
var match = (str || '').match(/^\[bkz:(.+)\]$/);
return match? match[1] : '';
}
extractKey('[bkz:sample key]'); //sample key
var aString = "[bkz:sample key]";
var regex = /^\[(.+)\:(.+)\]$/;
var matches = regex.exec(aString);
// "sample key" should now be in matches[2]

Variable reset to default option, WHY? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I do not understand how I keep ending up with "null" after variable is assigned a number.
function evalKayScript(syn){
coms = extract(syn,"{...}");
document.write(JSON.stringify(coms));//debug
for(x in coms){
ops = extract(coms[x],"(...)");
com = null; //<-- ***com preset null***
for(y in funNames){
if(ops[1] == funNames[y]){
com = y; //<-- ***com changed to "y"***
}
}
alert(com); <-- alerts given below (first two alerts)
if(com == null){
alert("Command ((("+ops[1]+"))) Not Registered!");
return null;
}
exe = funValues[y];
inputs = execVars(ops[2]);
inputs = extract(inputs,"[...]");
for(y in inputs){
exe.replace(new RegExp("/\(\%"+y+"\%\)/gim"),inputs[y]);
}
exe.replace(new RegExp("/\(\%name\%\)/gim"),ops[0]).replace(new RegExp("/\(\%function\%\)/gim"),ops[1]);
exea = exe;
if(exe.replace(new RegExp("/\:\:\:javascript/gim"),"")! = exes){ //<-- new invalid ":" error
eval(exe);
}else{
evalKayScript(exe);
}
}
}
I do not understand why, variable "com" goes to a number, then back to null...
I have setup some error catching in my own form, and i end up with these alerts:
0 //<-- var com
null //<-- ***var com? this makes no sense, how does it go back to null?***
Command ((("(%name%) already exists!"))) Not Registered! //<--caused by if(com == null) This is normal.
Live script at http://jstone88.bugs3.com/kayscript/file1.html, and JS file at http://jstone88.bugs3.com/kayscript/kayscript.js
You aren't using RegExp constructor as it should have been used.
It is like this:
new RegExp("pattern without / at the beginning an end","flags");
/pattern/flags is literal form of writing a regex in js, but it is different in RegExp constructor.

Jquery/Javascript Issue [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to query/javascript and having a problem with the following code to calculate a gross value and tax amount based
on the net amount the user enters. The user will enter a double amount and the gross and vat amounts are also defined as doubles.
Can anyone help? I get an error: "Uncaught SyntaxError: Unexpected number" when i try running the following code.
$('#netPayment').change(calcLowerVatRateAndGrossAmount);
/* $('#netPayment').change(function(){
calcLowerVatRateAndGrossAmount();
}); */
});
function calcVatRateAndGrossAmount(){
var netPayment = parseFloat($('#netPayment').val());
var vatAmount = 00.0;
var VatRate = 20.0;
var grossPayment = 0.00;
var totalPaymentAmount = 0.00;
if (netPayment !== '') {
vatAmount = (netPayment * VatRate) / 100;
grossPayment = (netPayment - vatAmount);
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
$('#grossPayment').val(parseFloat(grossPayment.data).toFixed(2));
} else {
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
}
};
So you calculate a number here
vatAmount = (netPayment * VatRate) / 100;
And in here, you treat vatAmount as an object that has a key data
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
You should just be using the variable. A simple test
console.log("variable itself: ", vatAmount);
console.log("key data: ", vatAmount.data);
So you would need to just do
$('#vatAmount').val(vatAmount.toFixed(2));
$('#grossPayment').val(grossPayment.toFixed(2));
You do the same thing with grossPayment and you reference some other property vatAmount.amountNull
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
should be
$('#vatAmount').val(""); //or any error message
$('#grossPayment').val("");

Categories