javascript validate swedish birthnumber - javascript

im trying to do a simple validation for an input who shall allow a number formated like this: 112233-1111 and when i accomplish that i would make it so that 22 cant exceed 12 and 33 exceed 31, this is what i got so far
var pn=document.forms.kontakt.pnr.value;
var spos=pn.indexOf("-");
var as= /^[0-9]{10}$/;
if (pn<11 || spos+4=pn.length || pn==null || pn=="")
{
alert ("Fyll i korrekt personnummer xxxxxx-xxxx");
kontakt.pnr.style.background = "red";
return false;
}
but it aint working, have i missed something?

There are a few problems here that I'd like to point out. First, spos+4=pn.length should be spos+4==pn.length (double equals because you are comparing). x does not seem to be defined and should be removed. Your regex variable as is never used.
Really, what you want to do is:
function calculate() {
//this matches 6 numbers followed by a ("-" or "+") followed by 4 more numbers
var as = /^[0-9]{6}[-+][0-9]{4}$/;
var pn=document.forms.kontakt.pnr.value;
if (as.test(pn)) {
var year = pn.substr(0,2);
var month = pn.substr(2,2);
var day = pn.substr(4,2);
//You probably need a better date checker, this is just an example
if (month <= 12 && day <= 30) {
document.body.innerHTML = 'great success!';
return;
}
}
document.body.innerHTML = 'Too bad!';
}
<form name="kontakt">
<input name="pnr" type="text" value="991222-1111"/>
<button type="button" onclick="calculate()">Calculate</button>
</form>

Related

character limit in a word inside a textarea dynamically

i am trying to put a limit on number of characters in a word. i am successful to find, if someone is entering more then 15 character.i am displaying a message right now. what i want to do is, if some one enter more then 15 characters ... the java script display a alert and then delete all letters leaving first 14 characters in that word. i tried to find some helpful functions but never found something useful.
i want to check for the character limit dynamically when the user is still entering.
my code is half complete but it has one flaw. it is displaying the message when a count is reaching more then 15 it displays a alert. now user can still save that string that has more than 15 char in a word. hope i explained it all.thanks to all,for everyone that is gonna put some effort in advance.
<textarea id="txt" name="area" onclick="checkcharactercount()"></textarea>
function checkcharactercount(){
document.body.addEventListener('keyup', function(e) {
var val = document.getElementById("txt").value;
var string = val.split(" ");
for(i=0;i<string.length; i++) {
len = string[i].length;
if (len >= 15) {
alert('you have exceeded the maximum number of charaters in a word!!!');
break;
}
}
});
}
Does this work like you want it to?
var textArea = document.getElementById('txt');
textArea.addEventListener('keyup', function () {
var val = textArea.value;
var words = val.split(' ');
for (var i = 0; i < words.length; i++) {
if (words[i].length > 14) {
// the word is longer than 14 characters, use only the first 14
words[i] = words[i].slice(0, 14);
}
}
// join the words together again and put them into the text area
textArea.value = words.join(' ');
});
<textarea id="txt" name="area"></textarea>

JQuery: Getting number from html element and alter it in Jquery/Javascript

I have some number printed on my html for special usage, therefore i need to grab it from html, alter it in javascript and output again.
So i have few numbers like below in my HTML:
<p id="usage">6564</p>
and i'd like to have a if statment in order do some modifcation of "6564",
below is some pseudo codes, which tells what i'd like to do.
var checker = $("#usage").html();
if(checker >= 2 digits){
//display the first two digits
}
else {
$("#usage").html("1");
}
The if statement should display the first two digits only, if the number has more than 2 digits otherwise it will return "10", So the result should be "65"
Solution :
For people who experience the same issues as me
var checker = $(".totalPage").text().replace(/,/g, ""); //it you have comma between your number like 6,545
var pagevalue = parseInt(checker.slice(0,2));
if(checker.length >= 2){
$(".totalPage").text(pagevalue+1);//you can modify the our put even further
}
else {
$(".totalPage").text("10");
}
var checker = $("#usage").text();
if(checker.length >= 2){
$("#usage").text(checker.slice(0,2));
}
else {
$("#usage").text("10");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="usage">6564</p>
Use slice to get the 2 digits.
Use length to tell if number has more than 2 digits
Here's the pure Js version.
function extractFunction() {
var checker = document.getElementById("usage").innerHTML;
if (checker.length > 2) { //if cheacker lentgh > 2
var result = checker.substr(0, 2); //start at char 1 and pull first 2 chars
document.getElementById("usage").innerHTML = result;
}
else{
document.getElementById("usage").innerHTML = "1";
}
}
<p id="usage">6564</p>
<button onclick="extractFunction()">Extract it</button>

Regex to replace non-numeric characters and insert dashes for phone number as it is typed

I need javascript to format a telephone number as it is typed. This would replace all non-numeric characters and insert dashes if the user doesn't type them in. So far this is the closest I've gotten, but it is thrown off if they put a dash in the wrong spot. The ideal solution would be to replace dashes only in the wrong spots. I was looking for a way to possibly replace the 4th and the 8th digit differently but haven't come up with a solution.
$('#TelephoneNo').keyup(function (ev) {
if (/[^0-9\-]/g.test(this.value))
{
this.value = this.value.replace(/[^0-9\-]/g, '');
}
if (/^(\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
});
Assuming you want the format "123-456-7890":
function formatPhoneNumber(s) {
var s2 = (""+s).replace(/\D/g, '');
var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
return (!m) ? null : m[1] + " -" + m[2] + "-" + m[3];
}
<html>
<head>
<script type="text/javascript">
function CheckNum(ev) {
var inputval=document.getElementById("TelephoneNo").value;
debugger
if(inputval){
if (/[^0-9\-]/g.test(inputval))
{
inputval = inputval.replace(/[^0-9\-]/g, '');
}
if(detectPosition()){
if (/^(\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
}
document.getElementById("TelephoneNo").value=inputval;
}
}
function detectPosition() { var inputval=document.getElementById("TelephoneNo").value;
if(inputval.indexOf("-") ==4 || inputval.indexOf("-") ==8)
{
return 1;
}
return -1;
}
</script>
</head>
<body>
<input type="text" id="TelephoneNo" onkeyup="CheckNum(this)">
</body>
</html>
I know this is an old question, but I figured I might help someone out.
I did this xxx-xxx-xxxx as-you-type formatting using two cases: one for formatting where the length required one hyphen, and another for formatting with two required. That way, the last group always expects an unknown char count and doesn't wait until the end of the user input to enforce the format.
function formatPhone() {
var element = document.getElementById('phone');
var inputValue = element.value;
// length < 3 : no formatting necessary
if (inputValue.length > 3 && inputValue.length < 8)
// length < 8 : only one hyphen necessary, after first group of 3
// replace (remove) non-digits, then format groups 1 and 2
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{0,3})/g, '$1-$2');
else
// length >= 8 : 2 hyphens required, after first two groups of 3
// replace (remove) non-digits, then format groups 1, 2, and 3
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{3})(.{0,4})/g, '$1-$2-$3');
element.value = result;
}
Type a phone number, it will be formatted to xxx-xxx-xxxx as you type:<br/><br/>
<input type="text" id="phone" maxlength="12" onkeyup="formatPhone()"></input>

split() loop: if string number = x, insert <br>

This question refers to one of mine about split(), and include an answered question about inserting specific thing if string number is x.
Basically, I have one big string, with a specific separator which is :, and I'm using .split() in a loop to print each part of the string into a different input using the separator to cut it. This works perfectly.
Now, what I want is to do a breakline after each 17 inputs (input 17 then linebreak, input 34 then linebreak, input 51...). I found a way to do it in the second link I shared, and the breakline works. The problem is that only the last line of inputs is now filled with the string parts (the last 7 parts of the string). All the other input are simply blank.
Here's the final code:
function cutTheString()
{
var str = document.getElementById('textareaString').value;
var arrayOfStrings = str.split(':');
for(var i = 0; i < arrayOfStrings.length; i++)
{
if ((i % 17) == 0)
{
document.getElementById('result').innerHTML += '<br />';
}
var div = document.getElementById('result');
var mi = document.createElement('input');
mi.setAttribute('type', 'text');
mi.setAttribute('size', '4');
mi.setAttribute('id', 'string' + (i+1));
div.appendChild(mi);
document.getElementById('string' + (i+1)).value = arrayOfStrings[i];
}
}
Interestingly, in if ((i % 17) == 0), let's replace 0 by x. If x < 17, only x - 17 inputs will be filled, starting by the last one of the list. If x > 17, all inputs will be filled, but the breaklines will obviously not work.
There is no error in the console, and my knowledge of Javascript makes me fail to understand why it's doing this. I quite see the correlation, but I can't think of any solution. I tried different operators than == without success.
You can test it on this JSFiddle. Thanks for your help!
Use
mi.setAttribute('value', arrayOfStrings[i]);
instead of
document.getElementById('string' + (i+1)).value = arrayOfStrings[i];
(before of div.appendChild(mi)).

2 or 4 Digit Date Validation with Javascript String Replacement

EDIT: To anyone making the same mistake I did in asking this question, please look for my amended answer below which demonstrates a MUCH cleaner solution to this problem.
Trying to permit user entry of either 2 digit or 4 digit date format and allow both to pass validation but autocorrect the 2 digit format with the 4 digit equivalent with the assumption that the leading 2 digits should be the same as the current leading 2 digits.
I'm having trouble with the javascript replace() function. This line:
input.replace(enteredDate, year);
is not working as expected. In the context of the spine.js framework I'm using, the input refers to $(event.target) and appears to be correct everywhere else in manipulating the input field where the validation should be occurring. Ultimately, I want to replace the original string found in the input field with the fully concatenated one (which I haven't built out yet), but for now, how can I replace the contents of input (where input is var = $(event.target)) with the var year assigned here:
var year = currentYear.charAt(0) + currentYear.charAt(1) + unparsedYear;
Here is the full code for the function I have so far, which is throwing the following error in reference to the .replace() line - Uncaught TypeError: Object [object Object] has no method 'replace'
validateDate: function(event) {
var input = $(event.target);
var enteredDate = input.val();
input.destroyValidationMessage();
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{2})|(\d{4})$/;
var result = enteredDate.match(pattern);
if (result !== null) {
var month = parseInt(result[1], 10);
var day = parseInt(result[2], 10);
var year = parseInt(result[3], 10);
var unparsedYear = parseInt(result[3], 10);
var unparsedYearStrLength = unparsedYear.toString().length;
if ( unparsedYearStrLength < 4) {
var currentYear = new Date().getFullYear().toString();
var year = currentYear.charAt(0) + currentYear.charAt(1) + unparsedYear;
alert('Autocorrected year will be ' + year);
input.replace(enteredDate, year);
}
var date = new Date(year, month - 1, day);
var isValid = date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
} else {
input.createValidationMessage('Invalid Date');
input.addClass('invalid');
}
}
As mentioned in my comment above:
input is a DOM element, but you actually want to replace the content of the element vs. the element itself, so use input.val(new_value) and not the actual input element.

Categories

Resources