javascript validation telephone - javascript

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.

Related

Creating a custom command as an alternative to setValue() where I can control the type speed

Hope someone can help with this. I have come across an issue with the application im testing. The developers are using vue.js library and there are a couple of fields which reformat the entered test. So for example if you enter phone number, the field will automatically enter the spaces and hyphens where its needed. This is also the same with the date of birth field where it automatically enters the slashes if the user does not.
So the issue I have is that using both 'setValue()' or 'sendKeys()' are entering the text too fast and the cursor in the field sometimes cannot keep up and the text entered sometimes appears in the incorrect order. For example, if I try to enter '123456789'. Some times it ends up as '132456798' (or any other combination). This cannot be produced manually and sometimes the test does pass. But its flakey.
What I wanted to do was to write a custom command to do something where it enters the string but in a slower manner. For this I need to have control of how fast I want the text to be entered. So I was thinking of something like this where I can pass in a selector and the text and then it will enter one character at a time with a 200 millisecond pause in between each character. Something like this:
let i = 0;
const speed = 200; // type speed in milliseconds
exports.command = function customSetValue(selector, txt) {
console.log(selector);
console.log(txt);
if (i < txt.length) {
this.execute(function () {
document.getElementsByName(selector).innerHTML += txt.charAt(i);
i++;
setTimeout(customSetValue, speed);
}, [selector, txt]);
}
return this;
};
When running document.getElementsByName(selector) in browser console I get a match on the required element. But it is not entering any text. Also note that I added a console.log in there and I was actually expecting this to log out 14 times but it only logged once. So itss as if my if condition is false
I checked my if condition and it should be true. So not sure why its not reiterating the function. Any help is much appreciated.
Also if it helps. I am using the .execute() command to inject javascript which is referenced here: https://nightwatchjs.org/api/execute.html
And the idea on this type writer is based on this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter
We ended up taking a different approach much simpler. Wanted to post here in case anyone else ever needs something similar
exports.command = function customSetValue(selector, txt) {
txt.split('').forEach(char => {
this.setValue(selector, char);
this.pause(200); // type speed in milliseconds
});
return this;
};

jQuery Regex Check on field works but alert message doesn't change

I have this function to validate postcodes (UK):
/* validate Post Code */
$.fn.validatePostCode = function(postcode)
{
regex = /^[A-Za-z]{1,2}\d{1,2}\s*\d{1}[A-Za-z]{2}$/i;
if (!regex.test(postcode)) {
return false;
}
};
as you can see it's just a simple regex checking for amount of character types at certain points.
To trigger it (or at least in the part I'm using it for) I use:
$(document).ready(function()
{
$('#nextBtn').on('click', function()
{
var postcode = $('#postcode').val();
console.log(postcode);
if (!$.fn.validatePostCode(postcode)) {
alert('hi');
} else {
alert('not valid');
}
});
});
doing the console.log is so I can see the value of the postcode each check, and I can see it updates. However, upon changing the input so I know it should be wrong still alert('hi') instead of Not Valid. I've even added a console.log in my validate function and that shows when the postcode is invalid, so why doesn't the alert message change each click?
I used this to validate my regex: http://www.regextester.com/ and it said my pattern was ok when I typed various postcodes in, so I'm a little lost at the moment, any ideas?
Thanks
Ok, so I found the solution rather quickly - it's because my function doesn't return a value until it fails. Needed to add a return true; outside of the if statement.
Hope this helps anyone who has a similar problem :)

Function to check for non valid characters on input... works randomly

Excuse me if the mistake is very silly, because I am just getting started with Javascript (and programming in general, by the way, I like it) I am trying to create a small program, and in one of the input fields, you have to write your name. I made a function to prevent that you include characters such as &%$?¿ and so on...
The problem is that the function works fine... sometimes yes, sometimes no... it seems to depend of where exactly you type the non valid characters, but due to my limited understanding of programming, I still cannot understand what am I doing wrong. Here, take a look:
function validate_input(text) {
var notgood = "!"·$%&/()=?¿##¬"; //cannot have this inside name
var i = 0;
while (i <= notgood.length) {
if (text.indexOf(notgood.charAt(i)) ==-1) {
ind = ind + 1;
break;
}
else {
alert("Your name cannot include symbols");
var text = prompt("Try again");
}
}}
A million thanks. Is just a small detail. I can have my input without checking for symbols, but I feel a bit silly of not being able to understand this problem...
You code might work, if you escape the second " in the notgood string:
var notgood = "!\"·$%&/()=?¿##¬";
Although I see many other potential issues, like the ind global.
Or you can try a regexp instead, it’s cleaner for your use case
var notgood = /[!"·$%&/()=?¿##¬]/; //cannot have this inside name
if ( notgood.test( text ) ) {
alert("Your name cannot include symbols");
text = prompt("Try again");
}

Replicate C# Server Side Validation in 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.

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