How to validate IP Address on multiple inputs? - javascript

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>

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 output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

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

form validation keep the information

I am trying to keep the information that you have already written even if you have an error in completing the form.Now if you have not written something correctly all the fields are cleaned and you have to start from the beginning.
This is the HTML
<form class="form" method="post" action="" name="registration" onsubmit="return formValidation()" >
<h2>Register now for free!</h2>
<label for="Fname">First name :</label>
<input type="text" name="Fname" id="Fname" placeholder="First Name">
<label for="Lname">Last name :</label>
<input type="text" name="Lname" id="Lname" placeholder="Last Name">
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="example#email.com">
<label for="password">Password :</label>
<input type="password" name="password" id="password" placeholder="******">
<label for="cpassword">Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword" placeholder="******">
<label id="gender">Gender : </label>
<input type="radio" name="sex" value="male"><span>Male</span>
<input type="radio" name="sex" value="female"><span>Female</span><br />
<input type="submit" id="submit" name="submit" value="Register">
</form>
This is the Javascript
function formValidation() {
var fName = document.getElementById("Fname").value;
var lName = document.getElementById("Lname").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var cpass = document.getElementById("cpassword").value;
if (fName_validation(fName, 20, 3)) {
if (lName_validation(lName, 20, 3)) {
if (email_validation(email)) {
if (pass_validation(pass, 20, 6)) {
}
}
}
}
function fName_validation(fName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!fName.match(check_name)) {
alert("First name should not be empty / length be between " + max + " to " + min);
fName.focus();
return false;
}
return true;
}
function lName_validation(lName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!lName.match(check_name)) {
alert("Last name should not be empty / length be between " + max + " to " + min);
lName.focus();
return ;
}
return true;
}
function email_validation(email) {
var checkk_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!email.match(checkk_email)) {
alert("Please enter a valid email!");
email.focus();
return ;
}
return true;
}
function pass_validation(pass, max, min) {
var check_password = /(?=.*\d)(?=.*[a-z]).{6,}/;
if (!pass.match(check_password)) {
alert("Your password should have at least one number,one letter and should be a least 6 characters!");
pass.focus();
return false;
}
if (pass !== cpass) {
alert("Password don't match!");
cpass.focus();
return false;
}
}
alert("Well Done!You successfully registered!");
return true;
}
make sure each validation method should return true or false.
please change two return ; to return false
I would not do this with JavaScript! Because HTML5 does the job for you. Therefore there are the <input> attributes required and pattern.
<input type="text" pattern="[A-Za-z]{2,20}" required="" />
The user should be informed which pattern he can use. And everything is fine.
Example

What condition for my javascript do I need? Its a script that pops up a dialogue box with form validation remarks for fields left blank

I have a form and a script that makes a dialogue box pop up if a field is left blank. The thing is, is that it only works if both fields are left blank. I'm trying to figure out how to get it to work correctly when and if one of the fields is left blank.
SCRIPT
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
if(sendMsg.mile.value=='' || isNaN(sendMsg.mile.value))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(sendMsg.location.value=='' || isNaN(sendMsg.location.value))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Form
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
Fixed it now, added input pattern to make sure only digits aswell as req'd on tags.Again I can't format the code in an answer so I'm adding another as I'd be here all night
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n in Numbers only\n";
}
if(location=='')
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="text" pattern="[0-9]+" class="form-control" data-validation-required-message="Please enter your Google Mileage" required id="mile" name="mile"/>
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" required placeholder="BUSINESS NAME" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
change:
isNaN(sendMsg.locaition.value)
to:
isNaN(sendMsg.location.value)
Try this
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="number" min="0" max="2000" class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value();
var location=document.getElementById("loc").value();
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(location=='' || isNaN(location))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>

Categories