To validate and connvert entered phone number in a form - javascript

I am working on an HTML form which has 4 fields as below
Name
Email
Phone Number
Message
The field for phone number should accept 10 digits. It change/accept of the format (xxx) xxx-xxxx when i click on the Message field.
I have written the function for javascript to do so but the number is not getting changed when i click on the message field. The code is below
It would be a great help if someone could help me out with this. Thanks in advance!
function PhoneValidation(phone) {
if (!(this.isNull)) {
var str = this.rawValue;
var regExp = /^\d{10}$/;
if (regExp.test(str)) {
this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(3, 3) + "-" + str.substr(6, 4);
} else {
regExp = /^[1-9]\d{2}\s\d{3}\s\d{4}$/;
if (regExp.test(str)) {
this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(4, 3) + "-" + str.substr(8, 4);
} else {
regExp = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
if (!(regExp.test(str))) {
xfa.host.messageBox("Please enter the telephone number in the format '(999) 999-9999'.");
this.rawValue = null;
xfa.host.setFocus(this);
}
}
}
}
}
And HTML below:
<form id="contact-form" class="contact-form" method="post" action="">
<div class="result"></div>
<input type="text" name="contact[name]" id="name" placeholder="Name *">
<input type="text" name="contact[email]" id="email" placeholder="E-mail *">
<input type="text" name="phone" id="phone" placeholder="Phone" onChange="PhoneValidation(this)" ;>
<textarea cols="5" rows="5" name="contact[message]" id="message" placeholder="Message *"></textarea>
<input type="submit" class="btn-dark" value="SEND">
</form>

in your validate function this = window, or something else so I have no idea what will !this.isNull actually do.
You may change it to something like
function PhoneValidation(phone) {
if(phone.value) {
// set up the phone.value here
}
}
// bind the change event as you did.
<input type="text" name="phone" id="phone" placeholder="Phone" onChange="PhoneValidation(this)";>
EDIT The code above is just the idea, please note that inside PhoneValidation in your case this = window. You have passed phone so try to use it, you can take the demo here http://jsfiddle.net/7qjz2/. As a summary
window.PhoneValidation = function(phone)
// cause I don't know where you put this js, so let bind it to window.
Next in side function, rawValue is undefined so use phone.value instead
If you can't pass the condition, set the html for your message div. by
document.getElementById("result").innerHTML = "Whatever you want"
That's all. Hope this help!

if (!(this.isNull)) {
Apparently, keep it short and simple like:
if (this) {

Related

Else is not executing ever

Im trying to do a form, in which you put your first name, surname and city, if inputs are empty or have number in them it should say Please fill out all of available boxes and make sure there are no numbers. Else it should say quote using all of input informations. But the else is not working.
I tried cahnging the code and swapping some variables.
function FillInfo()
{
/* proměnné */
var jmeno = document.forms ["SignUpForm"] ["jmeno"].value;
var prijmeni = document.forms ["SignUpForm"] ["prijmeni"].value;
var rok = document.forms ["SignUpForm"] ["mesto"].value;
/*Kontrola zdali input políčka jsou prázdná či pokud bylo zadáno číslo */
if(jmeno=="" || jmeno!=NaN || prijmeni=="" || prijmeni!= NaN || mesto=="" || mesto!=NaN){
document.getElementById("info").innerHTML = "Please fill out all of available boxes and make sure there are no numbers";
}
else{
document.getElementById("info").innerHTML = "Thank you" + " " + jmeno + " " + prijmeni + " from" + " " + mesto + "." + " " + "You are now being considered as our next adventurer. Good luck!";
}
}
<div class="heading2">
<div class="container2">
<p>Do you want to travel troughout space? Then fill out our form!</p><br>
<form name="SignUpForm">
<input type="text" name="jmeno" placeholder="First name" required><br>
<input type="text" name="prijmeni" placeholder="Last name" required><br>
<input type="text" name="mesto" placeholder="City" required><br><br>
<div id="info" class="well"></div>
<input type="button" class="otherpage" onclick="FillInfo();" value="Submit" /><br><br>
Return
</form>
</div>
</div>
Your if condition has to change, it always evaluates to true.
Instead of:
if (jmeno=="" || jmeno!=NaN || prijmeni=="" || prijmeni!= NaN || mesto=="" || mesto!=NaN) {
You should try:
if (jmeno==="" || isNaN(jmeno) || prijmeni==="" || isNaN(prijmeni) || mesto==="" || isNaN(mesto)) {
By the way, NaN is never equal to NaN, you have to use isNaN to know if it's a NaN.
However, this code is not what actually want. You want to check that there are no numbers, right? Depending on if you want no digits at all or no number-only values, you have to adapt your code. For example: !isNaN(Number(jmeno)) to check if the value is a number-only value. The values you get from the text inputs are always strings so the conversion is needed.
Your logic is wrong
jmeno=="" || jmeno!=NaN
Will always evaluate to true, I think you mean
jmeno=="" || isNaN(jmeno)
Obviously the rest of the statement needs editing too.

How to split string of input tag HTML?

When a user enters the below link in an input tag, I just want the last part of the string, in order to minimize input mistakes - the two input fields generate a new link that the user can copy and use.
name:id:5icOoE6VgqFKohjWWNp0Ac (I just want the last '5icOoE6VgqFKohjWWNp0Ac' part)
Can anyone help me with amending the below to achieve this?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
Here's a JavaScript function that takes a string as input, and formats it to only keep the last part after the last colon (if it contains a colon):
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
Eg. parseColon("a:b:c") would return "c"
You can validate your inputs with:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
In your code you can use these two functions to check & parse lName and fName like this:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>

if contact number is both empty and does not have 11 digits

id like my "Invalid contact number" to show if the text field is empty or if it does not contain 11 digits (if the text field has content)
HTML:
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
Javascript:
var contact = document.getElementById("contact").value;
if (!contact || (contact.val().length >=12 || contact.val().length <=10) ) {
document.getElementById("number_label").innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
} else {
document.getElementById("number_label").innerHTML = "Contact Number";
}
My "number_label" id in the if statement should change text and display the error.
It isn't working
You're calling .val() on contact (a String) which is no good. .val() is a jQuery method, and is meant to be called on the element itself.
the form just loads the "Invalid contact number" and reloads the page going back to the beginning
If you're trying to restrict a form from posting, make sure any path in your function that should restrict this has a return false.
var label = document.getElementById("number_label");
function validate() {
var contact = document.getElementById("contact").value;
if (!contact || contact.length !== 11) {
label.innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
return false;
} else {
label.innerHTML = "<b>Contact Number</b>";
}
}
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
<button onclick="validate()">Validate</button>
Your code has some errors. val() is not a function of the element.
if (!contact || (contact.**val()**.length >=12 || contact.**val()**.length <=10) ) {
Follows a fiddle with the code fixed. link

All Browsers seem to ignore JavaScript Client Side form validation rule

I've used JavaScript to ensure that the fields on my form are correctly filled out (required fields with correct type of information) and the browser seems to ignore the rules I set and process the information anyway.
HTML
HTML
<form id="course-form" name="courseForm" method="POST" onSubmit="return checkCourse()" action="#">
<label for="courseName">Course Name: </label>
<input type="text" id="course-name" name="courseName" placeholder="Course Name" required/><br/>
<br>
<label for="qualDesc">Description: </label><br/>
<textarea name="qualDesc" class="boxsizingBorder" placehold
<label for="entryReqs">Entry Requirements</label><br>
<textarea name="entryReqs" class="boxsizingBorder" id="entry-reqs" placeholder="Previous Grades Required" required></textarea><br>
<br>
<label for="cost">Cost: £</label>
<input type="text" name="cost" id="courseCost" maxlength="6" size="5" required/><br>
<br>
<input type="submit" value="Add Course" />
</form>
JavaScript(Placed in Head of document)
<script>
function checkCourse()
{
var date = new Date();
var year = (date.getFullYear());
var courseName=document.forms["courseForm"]["courseName"].value;
var courseDesc=document.forms["courseForm"]["qualDesc"].value;
var courseYear=document.forms["courseForm"]["year"].value;
var entryReqs=document.forms["courseForm"]["entryReqs"].value;
var cost=document.forms["courseForm"]["cost"].value;
if(courseName == "")
{
alert("Course name is a required field.");
return false;
}
else if(courseDesc=="")
{
alert("The Course needs a description");
return false;
}
else if(courseYear < year)
{
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);
return false;
}
else if(entryReqs=="")
{
alert("You must enter some entry requirements");
return false;
}
else if(isNaN(cost) || (cost==""))
{
alert("Cost is not a valid numerical figure");
}
alert("Course added sucessfully!");
return true;
}
</script>
**Note, I've also tried putting the return true section in an else statement like this:
else
{
alert("Course added sucessfully!");
return true;
}
Am I missing something?
Thanks
In the line below, you try to get the value of an input, but your form does not contain an input that is named year. This will cause a Javascript error and subsequently, your validation will be disregarded and the form will continue to submit
var courseYear=document.forms["courseForm"]["year"].value;
A second problem is you don't return false if the cost validation fails (but this is not your root problem).
Also as juvian points out, you are missing a closing quote on the alert below:
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);

Use user info without prompt or confirm?

All I want to do is be able to do is have users submit info and be able to use it - without using prompt.
I would like to have them be able to input and have a different box to be able to give them info based on there info. I.E. 81 is a great number.
var c = prompt("pick a number")
if(c>100){
console.log("110 is to high of a number")
}
This is what I have. I'm used to JavaScript editors and using console.log. I'm looking for a way to do that based on info I receive and be able to give feed back in a different <div> or whatever. Can anyone help?
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="submit" value="submit" />
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert(textbox.value + '\n' + location.value);
}
<input type="button" value="submit" onclick="showConfirmationDialog();" />
If you're using jQuery, you can use a click handler that looks like this:
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Here's a fiddle that shows the above code in action.

Categories