Using basic javascript - javascript

I have an input field whereby the user has to enter a phone number and it has to be exactly 10 numbers. My script isn't working and I'm wondering how to specify the 'exactly 10' part. At the moment it's just less than 10.
var contact_number = document.getElementById('number');
input = contact_number.value
if (input.length = 10){
alert("The field needs to contain 10 numbers!")
return false
}else {
return true
}
if (contact_number == ""){
alert("You need to enter a Phone Number")
return false;
}
<hr>
<!-- Clients details -->
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<p>Contact Number: <input id="number" name="number" type="number" maxlength="10" placeholder="Type Number here"></p>
<p>Email address: <input id="email" name="email" type="email" placeholder="Type Email here"></p>
<hr>

You can use the not equal operator !=
var contact_number = document.getElementById('number');
input = contact_number.value
if (input.length != 10){
alert("The field needs to contain 10 numbers!")
return false
}else {
return true
}
if (contact_number == ""){
alert("You need to enter a Phone Number")
return false;
}
<hr>
<!-- Clients details -->
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<p>Contact Number: <input id="number" name="number" type="number" maxlength="10" placeholder="Type Number here"></p>
<p>Email address: <input id="email" name="email" type="email" placeholder="Type Email here"></p>
<hr>

It looks like your first if-statement is off. I think you want it to say not equals. What you have currently is not a comparison, and will always go into the body of the if statement.
if (input.length != 10){
alert("The field needs to contain 10 numbers!")
return false
}

Related

Form Validation in JQuery Mobile

I'm trying to add validation to the form I made
<fieldset>
<legend>ENTER YOUR INFORMATION HERE FOR DELIVERY</legend>
<form action="" name="deliveryform">
Name* :<input type="text" name="name" id="name">
Phone Number* : <input type="text" name="phonenumber" id="phonenumber">
<span id="warning1"></span>
Address* : <textarea name="address" id="address" required></textarea>
Email* : <input type="text" name="email" id="email">
<span id="warning2"></span>
<input type="submit" id="submitbutton" value="Submit" onsubmit=" return validation()">
</form>
</fieldset>
Javascript
function validation()
{
var name = document.getElementsByName("name").value;
var phonenumber =document.getElementsByName("phonenumber").value;
var email = document.getElementById("email").value;
var emailformat = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$";
if(name == ""|| null)
{
alert("Please Enter Your Name!");
return false;
}
if(isNaN (phonenumber))
{
document.getElementById("warning1").innerHTML ="Enter numbers only";
return false;
}
if(!email.match(emailformat))
{
document.getElementById("warning2").innerHTML="Please enter the correct format. Example : Abc1234#gmail.com"
return false;
}
else
{
alert("Submitted Successfully")
}
}
Nothing changed except ''Error Loading Page '' message appeared.
Did I miss something?
I thought coding in without and with Jquery in HTML is the same thing..

Why the regular expression matches input but the alert still happens?

I made a simple page to validate input. but even my input matches the regular expressions, all three alerts still happen. Could you please help me figure it out? Thanks
<script>
function validate() {
var tel = document.getElementById("tel").innerHTML;
var email = document.getElementById("email").innerHTML;
var pcode = document.getElementById("pcode").innerHTML;
var tvalid = /^(\d{3}-\d{3}-\d{3}-\d{4})$/;
if(!tvalid.test(tel)) {
alert("Not a valid Phone Number");
}
if (!(/#gmail\.com$/.test(email)) && !(/#hotmail\.com$/.test(email)) && !(/#outlook\.com$/.test(email)) ) {
alert("Not a valid email");
}
var pvalid = /^([A-Z][A-Z]\d{2}-[a-z]\d[A-Z]\d)$/;
if(!pvalid.test(pcode)){
alert("Not a valid postal code.");
}
}
</script>
html
<label for="tel">Phone Number</label>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="xxx#(gmail/hotmail/outlook).com" required><br>
<label for="pcode">Postal Code</label>
<input type="text" id="pcode" name="pcode" placeholder="AA11-c1V2"><br>
<button type = "button" id="submit" onclick="validate()">Validate</button>
The reason why your code returns invalid for all inputs is because youre not actually testing it against the entered input, rather an empty string ''.
.innerHTML will return an empty string since there is no HTML between the start and end of your input tags.
To get the value of a control try using something like var tel = document.getElementById("tel").value;
This will return the actual user input.
So your code should look like this:
function validate() {
var tel = document.getElementById("tel").value;
var email = document.getElementById("email").value;
var pcode = document.getElementById("pcode").value;
var tvalid = /^(\d{3}-\d{3}-\d{3}-\d{4})$/;
if (!tvalid.test(tel)) {
alert("Not a valid Phone Number");
}
if (!(/#gmail\.com$/.test(email)) && !(/#hotmail\.com$/.test(email)) && !(/#outlook\.com$/.test(email))) {
alert("Not a valid email");
}
var pvalid = /^([A-Z][A-Z]\d{2}-[a-z]\d[A-Z]\d)$/;
if (!pvalid.test(pcode)) {
alert("Not a valid postal code.");
}
}
<label for="tel">Phone Number</label>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="xxx#(gmail/hotmail/outlook).com" required><br>
<label for="pcode">Postal Code</label>
<input type="text" id="pcode" name="pcode" placeholder="AA11-c1V2"><br>
<button type="button" id="submit" onclick="validate()">Validate</button>

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

How to validate IP Address on multiple inputs?

I am trying to check if what I submit via an input type="text" is a valid IP Address.
I have found this example online for JS IP Validation but it is only for one input and I have 4.
The inputs:
<form method="POST" name="simple_form" action="/staticIP" onsubmit="return ValidateIPaddress()">
<div class ="text_input">
<input type="text" placeholder="Network Name (SSID)" name="networkName" value="" pattern=".{5,30}" title="Enter between 5 and 30 characters">
</div>
<div class="text_input">
<input type="password" placeholder="Password" name="networkPassword" value="" minlength="8" pattern=".{8,63}" title="Enter between 8 and 63 characters">
</div>
<div class ="text_input">
<input type="text" placeholder="IP Address" name="ipAddress" value="" required>
</div>
<div class="text_input">
<input type="text" placeholder="Gateway" name="gateway" value="" required>
</div>
<div class ="text_input">
<input type="text" placeholder="Subnet Mask" name="subnet" value="" required>
</div>
<div class ="text_input">
<input type="text" placeholder="DNS" name="dns" value="" required>
</div>
<input class="button" type="submit" name="" value="Save and Reboot">
</form>
JS:
<script>
function ValidateIPaddress()
{
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var ipaddr = document.forms["simple_form"]["ipAddress"];
var gateway = document.forms["simple_form"]["gateway"];
var subnet = document.forms["simple_form"]["subnet"];
var dns = document.forms["simple_form"]["dns"];
var counter = 0;
if(ipaddr.value.match(ipformat)) {
ipaddr.focus();
} else {
window.alert("You have entered an invalid IP Address!");
ipaddr.focus();
return (false);
}
if(gateway.value.match(ipformat)) {
gateway.focus();
} else {
window.alert("You have entered an invalid GATEWAY Address!");
gateway.focus();
return (false);
}
if(subnet.value.match(ipformat)) {
subnet.focus();
} else {
window.alert("You have entered an invalid SUBNET Address!");
subnet.focus();
return (false);
}
if(dns.value.match(ipformat)) {
dns.focus();
} else {
window.alert("You have entered an invalid DNS Address!");
dns.focus();
return (false);
}
}
</script>
As you can see I don't have any return(true). Do I need it ?
Also, this makes me need to input all of the values before it can actually check them.
Is there any other way of checking them individually ?
I also have found some Regex rules here:
pattern = " (?<!\S)((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b|\.\b){7}(?!\S) "
/* or */
pattern="^([1-9]|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$"
They seem to work, but I want to try using JS.
Response:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script>
function ValidateIPaddressOnChange(input, type)
{
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
switch(type){
case "ipaddress": type = "IP Address"; break;
case "gateway": type = "Gateway"; break;
case "subnet": type = "Subnet Mask"; break;
case "dns": type = "DNS"; break;
}
if(!input.value.match(ipformat)) {
document.getElementById(input.name).className =
document.getElementById(input.name).className.replace
( /(?:^|\s)correct(?!\S)/g , '' )
document.getElementById(input.name).className += " wrong";
input.focus();
alert(type + " is invalid!");
return(false);
}
else if(input.value != null){
document.getElementById(input.name).className =
document.getElementById(input.name).className.replace
( /(?:^|\s)wrong(?!\S)/g , '' )
document.getElementById(input.name).className += " correct";
}
}
function ValidateIPaddress()
{
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var ipaddr = document.forms["simple_form"]["ipAddress"];
var gateway = document.forms["simple_form"]["gateway"];
var subnet = document.forms["simple_form"]["subnet"];
var dns = document.forms["simple_form"]["dns"];
var counter = 0;
if(ipaddr.value.match(ipformat)) {
ipaddr.focus();
} else {
alert("You have entered an invalid IP Address!");
ipaddr.focus();
return (false);
}
if(gateway.value.match(ipformat)) {
gateway.focus();
} else {
window.alert("You have entered an invalid GATEWAY Address!");
gateway.focus();
return (false);
}
if(subnet.value.match(ipformat)) {
subnet.focus();
} else {
window.alert("You have entered an invalid SUBNET Address!");
subnet.focus();
return (false);
}
if(dns.value.match(ipformat)) {
dns.focus();
} else {
window.alert("You have entered an invalid DNS Address!");
dns.focus();
return (false);
}
}
</script>
<form method="POST" name="simple_form" action="/staticIP" onsubmit="return ValidateIPaddress()">
<div class ="input_row">
<input type="text" class="input_text" placeholder="Type here Network Name (SSID)" id="networkName" name="networkName" value="" pattern=".{5,30}" title="Enter between 5 and 30 characters" required />
<label class="label_" for="networkName">Network Name (SSID)</label>
</div>
<div class="input_row">
<input type="password" class="input_text" placeholder="Type here Password" id="networkPassword" name="networkPassword" value="" minlength="8" pattern=".{8,63}" title="Enter between 8 and 63 characters" required />
<label class="label_" for="networkPassword">Password</label>
</div>
<div class ="input_row">
<input type="text" class="input_text" placeholder="Type here IP Address" id="ipAddress" name="ipAddress" value="" required
onchange="ValidateIPaddressOnChange(this, 'ipaddress')" />
<label class="label_" for="ipAddress">IP Address</label>
</div>
<div class="input_row">
<input type="text" class="input_text" placeholder="Type here Gateway" id="gateway" name="gateway" value="" required
onchange="ValidateIPaddressOnChange(this, 'gateway')" />
<label class="label_" for="gateway">Gateway</label>
</div>
<div class ="input_row">
<input type="text" class="input_text" placeholder="Type here Subnet Mask" id="subnet" name="subnet" value="" required
onchange="ValidateIPaddressOnChange(this, 'subnet')" />
<label class="label_" for="subnet">Subnet Mask</label>
</div>
<div class ="input_row">
<input type="text" class="input_text" placeholder="Type here DNS" id="dns" name="dns" value="" required
onchange="ValidateIPaddressOnChange(this, 'dns')" />
<label class="label_" for="dns">DNS</label>
</div>
<input class="button" type="submit" name="" value="Save and Reboot">
</form>
You would want to wrap the algorithm in a reusable function instead
function ValidateIPaddressOnChange(input, type)
{
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var strtype = "";
switch(type){
case "ipaddress": strtype = "IP Address"; break;
case "gateway": strtype = "gateway"; break;
case "dns": strtype = "DNS"; break;
case "subnet": strtype = "subnet mask"; break;
}
if(!input.value.match(ipformat)) {
input.focus();
alert("You have entered an invalid " + strtype + " format!");
}
}
In your HTML, attach an onchange event on the input element, which will then execute an individual validation whenever the user finishes changing the inputs
<input type="text" name="networkName" value="" pattern=".{5,30}" title="Enter between 5 and 30 characters" onchange="ValidateIPaddressOnChange(this, 'ipaddress')" />
You can keep your old validation function, that one actually validates everything on submission, which is also fine and dandy. There are obviously better ways to do this, but for now, this can do without diverging much from what you already started.
You can use the match() to match your regex to the input and check if it's correct format
Example of valid IP address
115.42.150.37
192.168.0.1
110.234.52.124
var pattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
function check() {
$.each($(".ip"), function() {
if (!$(this).val().match(pattern)) {
$(this).addClass("wrong");
$(this).removeClass("correct");
} else {
$(this).addClass('correct');
$(this).removeClass("wrong");
}
});
}
.wrong {
color: red;
}
.correct {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="ip" /><br>
<input class="ip" /><br>
<input class="ip" /><br>
<input class="ip" /><br>
<button onClick="check()">Check ip address</button>

Submitting Form W/ Javascript

My javascript form validation is working correctly. I want it so that when the form is valid, it will go to a different page. I am having trouble with that part. I tried using the document object to submit it if everything is valid but its not working
Javascript:
function func(){
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var email = document.getElementById('mail').value;
var phone = document.getElementById('phone').value;
var val_phone = /^\(\d{3}\)\d{3}-\d{4}$/;
var val_mail = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ( first == "" || last == "" || email == "" || phone == "")
{
alert("Do not Leave Any Blank Answers");
return;
}
if ( phone != phone.match(val_phone) || email != email.match(val_mail) )
{
alert("Incorrect Format! \n Please Check Email and Phone Number! ");
return;
}
else {
document.forms["survey"].sumbit();
}
}
HTML:
<form id="survey" name="survey" action="SlideShow.html" method="post">
First Name:<br>
<input type="text" id="fname" name="fname" required="required"><br>
Last Name:<br>
<input type="text" id="lname" name="lname" required="required"><br>
Email:<br>
<input type="email" id="mail" name="mail" required="required"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone" required="required"><br><br>
<input type="button" value="Submit" onclick="func()">
</form>
Your else block is calling sumbit(), but the proper spelling is submit().
Additionally, I recommend getting in the habit of a strict === check as opposed to a ==.
Here's a JSFiddle with the updated and refactored code:
http://jsfiddle.net/cyeof94g/

Categories