Javascript validation, link together with the form? - javascript

I need help to get this working. I have done a script that validate the field "Personalnumber". But i dont know how to link the togheter and get it working.
Can someone help?
//If the form looks weird, i have deleted all the other fields just to get a shorter code.
<script>
function validatePNum(sPNum)
{
var numbers = sPNum.match(/^(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)$/);
var checkSum = 0;
var d = new Date();
if (!isDate(sPNum.substring(0,4),sPNum.substring(4,6),sPNum.substring(6,8))) {
alert("Datumet " + sPNum.substring(0,8) + " är inte korrekt.");
return false;
}
if (numbers == null) { return false; }
var n;
for (var i = 3; i <= 12; i++)
{
n=parseInt(numbers[i]);
if (i % 2 == 0) {
checkSum+=n;
} else {
checkSum+=(n*2)%9+Math.floor(n/9)*9
}
}
if (checkSum%10==0) { return true;}
return false;
}
function getYear(y) { return (y < 1000) ? y + 1900 : y; }
function isDate(year, month, day)
{
month = month - 1; // 0-11 in JavaScript
var tmpDate = new Date(year,month,day);
if ( (getYear(tmpDate.getYear()) == year) &&
(month == tmpDate.getMonth()) &&
(day == tmpDate.getDate()) )
return true;
else
return false;
}
</script>
<form method="post" name="post" action="index.php?site=register">
<tr>
<td class="border_1" align="left">Personnummer:</td>
<td class="border_1"><input id="personalnumber" type="text" name="personalnumber" value="$personalnumber" size="30"/><small> YYYYMMDDXXXX</small></td>
</tr>
<div align="center"><input name="save" type="submit" value="Registera" /></div>
</form>

First of all change the name in your form to something like name="myForm". Then, you can link your JS code with your form by taking the value of the field, ie var x = document.forms["myForm"].value;. Not tested, but this is a way to link your js code with the form in your html.

You Can use jQuery
just add to your form id (like form_id in my example).
$('#form_id').submit(function(){
validatePNum(sPNum)
//do more things
});

Related

Javascript function to every textfield that calls the function

I have written a simple javascript function that takes the input of a date textfield and convert it to dd-mm-yyyy format.
function dateConvert(dateValue) {
if(dateValue == null) {
var grDate = null;
}
else {
var n = dateValue.search("/");
if( n >= 0) {
var res = dateValue.split("/");
var day = res[0];
if( day.length == 1 ) {
day = "0"+day;
}
var month = res[1];
if( month.length == 1 ) {
month = "0"+month;
}
var year = res[2];
var grDate = day+"-"+month+"-"+year;
/*alert(grDate);*/
}
else {
var grDate = dateValue;
}
}
document.getElementById("mydate").value = grDate;
}
<input type="text" name="mydate" id="mydate" onblur="dateConvert(this.value)" />
Is there a way to make function "global" and use it to every textfield that calls the function without having to write it e.g. 3 times if I want to use it in 3 different date textfields?
Thanks for the replay to Dominik. Make my mind spin
I didn't use event listener but querySelectorAll
Here is the correct version. It works fine
function myFunction() {
var x = document.querySelectorAll(".mydate");
var i;
for (i = 0; i < x.length; i++) {
var dateValue = x[i].value;
if(dateValue == null) {
var grDate = null;
}
else {
var n = dateValue.search("/");
if( n >= 0) {
var res = dateValue.split("/");
var day = res[0];
if( day.length == 1 ) {
day = "0"+day;
}
var month = res[1];
if( month.length == 1 ) {
month = "0"+month;
}
var year = res[2];
var grDate = day+"-"+month+"-"+year;
/*alert(grDate);*/
}
else {
var grDate = dateValue;
}
}
x[i].value = grDate;
}
}
for inputs
<p><input type="text" name="field1" class="mydate" onblur="myFunction()" /></p>
<p><input type="text" name="field2" class="mydate" onblur="myFunction()" /></p>
<p><input type="text" name="field3" class="mydate" onblur="myFunction()" /></p>
Excellent question - because this is the perfect example where a custom element solves the problem.
It's really easy:
customElements.define('my-date', class extends HTMLInputElement {
constructor() {
super();
this.dateConvert = this.dateConvert.bind(this);
this.addEventListener('blur', this.dateConvert);
}
dateConvert() {
if (this.value) {
let n, res, day, month, year;
n = this.value.search("/");
if (n >= 0) {
res = this.value.split("/");
day = res[0];
if (day.length == 1) {
day = "0" + day;
}
month = res[1];
if (month.length == 1) {
month = "0" + month;
}
year = res[2];
this.value = `${day}-${month}-${year}`;
}
}
}
}, { extends: 'input' });
<input is="my-date" />
Now you can even add new date inputs dynamically and they come with your behaviour automatically. No fuddling around in the DOM, just an element that does exactly what you need any time it's in the HTML anywhere.
Please note that unfortunately Safari does not support customizing built-in elements, so you either will have to resort to a polyfill (check https://github.com/webcomponents/polyfills/tree/master/packages/custom-elements or https://github.com/ungap/custom-elements#readme) for that, or use an autonomous custom elements like this:
customElements.define('my-date', class extends HTMLElement {
constructor() {
super();
this.input = document.createElement('input');
this.appendChild(this.input);
this.dateConvert = this.dateConvert.bind(this);
this.input.addEventListener('blur', this.dateConvert);
}
dateConvert() {
if (this.value) {
let n, res, day, month, year;
n = this.value.search("/");
if (n >= 0) {
res = this.value.split("/");
day = res[0];
if (day.length == 1) {
day = "0" + day;
}
month = res[1];
if (month.length == 1) {
month = "0" + month;
}
year = res[2];
this.value = `${day}-${month}-${year}`;
}
}
}
get value() {
return this.input.value;
}
set value(val) {
this.input.value = val;
}
});
<my-date></my-date>
Just as a sidenote, you might want to consider using the built-in API for dateTime conversion/formatting:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

Masking the values in a textbox using jQuery

I have a textbox and onkeyup event I have to mask (with asterisk (*) character) a portion of the string (which is a credit card number) when user enter the values one after the other. e.g. say the value that the user will enter is 1234 5678 1234 2367.
But the textbox will display the number as 1234 56** **** 2367
I general if the user enters XXXX XXXX XXXX XXXX, the output will be XXXX XX** **** XXXX where X represents any valid number
The program needs to be done using jQuery. I have already made the program (and it is working also) which is as follows:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $(this).val();
var CCNLength = CCNValue.length;
$.each(CCNValue, function(i) {
if (CCNLength <= 7) {
$("#txtCCN").val(CCNValue);
} //end if
if (CCNLength >= 8 && CCNLength <= 14) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, CCNLength).replace(/[0-9]/g, "*"));
} //end if
if (CCNLength >= 15) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/[0-9]/g, "*") + CCNValue.substring(15));
} //end if
});
});
});
</script>
</head>
<body>
<input type="text" id="txtCCN" maxlength=19 />
</body>
</html>
But I think that the program can be optimized/re-written in a much more elegant way.
N.B. I don't need any validation at present.
No need of any condition of length, substring and replace can be directly used on the string of any length safely.
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $.trim($(this).val());
$(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/\d/g, "*") + CCNValue.substring(15));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
val can also be used
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
$(this).val(function(i, v) {
return v.substring(0, 7) + v.substring(7, 15).replace(/\d/g, "*") + v.substring(15);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
The same can be done in VanillaJS
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('txtCCN').addEventListener('keyup', function() {
var value = this.value.trim();
this.value = value.substring(0, 7) + value.substring(7, 15).replace(/\d/g, '*') + value.substring(15);
}, false);
});
<input type="text" id="txtCCN" required maxlength="19" />
Try It: Its 100% workable...
$(document).ready(function () {
$("#txtCCN").keyup(function (e) {
var CCNValue = $(this).val();
CCNValue = CCNValue.replace(/ /g, '');
var CCNLength = CCNValue.length;
var m = 1;
var arr = CCNValue.split('');
var ccnnewval = "";
if (arr.length > 0) {
for (var m = 0; m < arr.length; m++) {
if (m == 4 || m == 8 || m == 12) {
ccnnewval = ccnnewval + ' ';
}
if (m >= 6 && m <= 11) {
ccnnewval = ccnnewval + arr[m].replace(/[0-9]/g, "*");
} else {
ccnnewval = ccnnewval + arr[m];
}
}
}
$("#txtCCN").val(ccnnewval);
});
});
One thing you might consider is deleting the first two if statements. All of the work your function does is contained within the last one, so you could just change it from
if(CCNLength >= 15)
to
if(CCNLength >= 8)
This seems to maintain the functionality while cutting out some repetition in your code.
Adding a generic routine for customizing space points and mask range in the input data. This will also respect the space characters as you originally asked for.
$(function () {
$("#cardnum").keyup(function (e) {
var cardNo = $(this).val();
//Add the indices where you need a space
addSpace.call(this, [4, 9, 14], cardNo );
//Enter any valid range to add mask character.
addMask.call(this, [7, 15], $(this).val()); //Pick the changed value to add mask
});
function addSpace(spacePoints, value) {
for (var i = 0; i < spacePoints.length; i++) {
var point = spacePoints[i];
if (value.length > point && value.charAt(point) !== ' ')
$(this).val((value.substr(0, point) + " "
+ value.substr(point, value.length)));
}
}
function addMask(range, value) {
$(this).val(value.substring(0, range[0])
+ value.substring(range[0], range[1]).replace(/[0-9]/g, "*")
+ value.substring(range[1]));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cardnum" maxlength="19" />

Allow to select only predifened combination from available values

let us say we have parameter with A,B,C and D values. Now we want to force the user to choose only A,B,C or A,C,D or A or B or C.
Instead of Allowing all possible 16 combination, we want to allow only 5 predefined combination. I tried it but for this i have to put condition for each and every selection.
If we assume this values are bind with checkbox and we need to check whether selected values are as per our predifined combination or not.
I need to achieve this in javascript or either angular.js. Please help me with proper algorithm for such operation.
I tried below logic to achieve this but this will not infor user instantly, alert only after final submission
// multi-dimentional array of defined combinations
var preDefinedCombinations = [['a','b','c'], ['a','c','d'], ['a'], ['b'], ['c']];
// Combination user select
var selectedvalues = [];
// Function called on selection or removing value (i.e a,b,c,d)
function selectOption(value){
var checkIndex = selectedvalues.indexof(value);
if(checkIndex == -1){
selectedvalues.push(value);
}else{
selectedvalues.splice(checkIndex, 1);
}
}
// function called on submition of combination
function checkVaildCombination(){
if(preDefinedCombinations.indexOf(selectedvalues) == -1){
alert('Invalid Combination');
}else{
alert('Valid Combination');
}
}
This code gives information only about combination is valid or not, not about which may be possible combinations as per selections.
stolen from https://stackoverflow.com/a/1885660/1029988 :
function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = new Array();
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
then in your code:
function checkVaildCombination(){
function get_diff(superset, subset) {
var diff = [];
for (var j = 0; j < superset.length; j++) {
if (subset.indexOf(superset[j]) == -1) { // actual missing bit
diff.push(superset[j]);
}
}
return diff;
}
if(preDefinedCombinations.indexOf(selectedvalues) == -1){
missing_bits = [];
diffed_bits = [];
for (var i = 0; i < preDefinedCombinations.length; i++) {
var intersection = intersect_safe(preDefinedCombinations[i], selectedvalues);
if (intersection.length == selectedvalues.length) { // candidate for valid answer
missing_bits.push(get_diff(preDefinedCombinations[i], intersection));
} else {
var excess_bits = get_diff(selectedvalues, intersection),
missing_bit = get_diff(preDefinedCombinations[i], intersection);
diffed_bits.push({
excess: excess_bits,
missing: missing_bit
});
}
}
var message = 'Invalid Combination, if you select any of these you`ll get a valid combination:\n\n' + missing_bits.toString();
message += '\n\n Alternatively, you can reach a valid combination by deselected some bits and select others:\n';
for (var j = 0; j < diffed_bits.length; j++) {
message += '\ndeselect: ' + diffed_bits[j].excess.toString() + ', select: ' + diffed_bits[j].missing.toString();
}
alert(message);
} else {
alert('Valid Combination');
}
}
you will of course want to format the output string, but that code will (hopefully, it is napkin code after all) give you the missing bits to make valid combos with what you've got selected already
May be following code could help you to solve ur problem
<script>
function validateForm(){
var checkBoxValues = this.a.checked.toString() + this.b.checked.toString() + this.c.checked.toString() + this.d.checked.toString();
if( checkBoxValues == 'truetruetruefalse' || // abc
checkBoxValues == 'truefalsetruetrue' || // acd
checkBoxValues == 'truefalsefalsefalse' || // a
checkBoxValues == 'falsetruefalsefalse' || // b
checkBoxValues == 'falsefalsetruefalse' ){ // c
return true;
}
return false;
}
</script>
<form onsubmit="return validateForm()" action="javascript:alert('valid')">
<input type="checkbox" name="mygroup" id="a">
<input type="checkbox" name="mygroup" id="b">
<input type="checkbox" name="mygroup" id="c">
<input type="checkbox" name="mygroup" id="d">
<input type="submit">
</form>

jQuery multiple validation

I have here a form validation. I used this validation in multiple editing records in php. I have two textbox that comparing it's value. I tried to mix my validation script and comparing value script but isn't working properly.
This what I have now but I'm having problem with this when I tried to input lower value in n_quanity field the validation error message is not working and it allowed the form to submit. I want to display error in span not alert the message. Help please?
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
for (var i = 0,len=textBox1.length; i < len;i++) {
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
return false;
} else {
$(this).next("span.val_qty").html("");
}
}
});
And this is my full code
<script>
jQuery(function($) {
var validation_holder;
$("form#register_form input[name='submit']").click(function() {
var validation_holder = 0;
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else {
$(this).next("span.val_qty").html("");
}
});
if(validation_holder == 1) { // if have a field is blank, return false
$("p.validate_msg").slideDown("fast");
return false;
} validation_holder = 0; // else return true
/* validation end */
}); // click end
}); // jQuery End
</script>
<script>
$('#sbtBtn').on('click', function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0,len=textBox1.length; i < len;i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
alert('value is greater than quantity');
return false;
} else {}
}
});
</script>
<p> <label for="">PR Quantity</label> <input name="n_quantity[]" id="n_quantity" class="qty n_quantity" type="text"/><span class="val_qty"></span> </p>
<p style="display:none;"><input id="pr_total" class="pr_total" type="text"></p>

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Categories