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
Related
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..
When writing for special characters in password, it does not pass through, only the empty field and 6 character limit are egistered. I checked a bunch of places but I still get no result no matter where I look. When the regex was not there the confirm password entries worked as well, so something is out of place
Javascript:
function VerifyAndConfirmPassword()
{
var pw = document.forms["form"]["passPass"].value;
var pwC = document.forms["form"]["passCPass"].value;
if(pw == "")
{
alert("Password field is required");
return false;
}
if(pw.length < 6)
{
alert("Password length must be atleast 6 characters");
return false
}
var validPass = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]$/
if(!pw.value.match(validPass))
{
alert("Password requires at least one capital and lowercase letter , one number, and one special character")
return false;
}
if(pwC == "")
{
alert("Confirm Password field is required");
return false;
}
if(pw != pwC)
{
alert("Passwords do not match");
return false;
}
else
{
return true;
}
}
function VerifyAndConfirmPassword()
{
var pw = document.forms["form"]["passPass"].value;
var pwC = document.forms["form"]["passCPass"].value;
if(pw == "")
{
alert("Password field is required");
return false;
}
if(pw.length < 6)
{
alert("Password length must be atleast 6 characters");
return false
}
var validPass = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]$/
if(!pw.value.match(validPass))
{
alert("Password requires at least one capital and lowercase letter , one number, and one special character")
return false;
}
if(pwC == "")
{
alert("Confirm Password field is required");
return false;
}
if(pw != pwC)
{
alert("Passwords do not match");
return false;
}
else
{
return true;
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content = "width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="Assignment4.css">
</head>
<body>
<form name="form" onsubmit="return FirstName() && LastName() && Address() && City() && PostalCode() && ProvinceValues() && Age() && VerifyAndConfirmPassword() && Email()" method="post" action="mailto:jjohn#JJohnsonRE.ca">
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="txtFirst" maxlength="100" placeholder="Your First Name"><br><br>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="txtLast"maxlength="100" placeholder="Your Last Name"><br><br>
<label for="address">Address:</label><br>
<input type="text" name="txtAdd" maxlength="100" placeholder="Address"><br><br>
<label for="city">City:</label><br>
<input type="text" name="txtCity" maxlength="100" placeholder="City"><br><br>
<label for="postalCode">Postal Code:</label><br>
<input type="text" name="txtPC" maxlength="100" placeholder="Postal Code"><br><br>
<label for="province">Province: (Must use initials)</label><br>
<input type="text" id="txtPro" maxlength="100" placeholder="Province"><br><br>
<label for="age">Age:</label><br>
<input type="number" name="numAge" maxlength="100" placeholder="Age"><br><br>
<label for="password">Password:</label><br>
<input type="password" name="passPass" id="passPass" maxlength="100" placeholder="Password"><br><br>
<span id="message"></span>
<label for="Cpassword">Confirm Password:</label><br>
<input type="password" id="passCPass" name="passCPass" maxlength="100" placeholder="Password"><br><br>
<span id="messageC"></span>
<span id="confirm"></span>
<label>Your Email:</label><br>
<input name="txtEmail" type="text" maxlength="100" placeholder="Email"><br><br>
<input type="submit" value="Register Now">
<input type="reset" value="Clear Form">
</form>
<script src="Assignment4.js"></script>
</body>
</html>
!pw.value.match(validPass)
pw is already the value of the input field (defined as document.forms["form"]["passPass"].value). Getting the value property of a String returns null, and thus you get the error. Just use simply:
!pw.match(validPass)
You should also be returning the result of VerifyAndConfirmPassword() on submit, not FirstName() && LastName() && Address() && City() && PostalCode() && ProvinceValues() && Age() && VerifyAndConfirmPassword() && Email().
Use:
function VerifyAndConfirmPassword() {
var pw = document.forms["form"]["passPass"].value;
var pwC = document.forms["form"]["passCPass"].value;
if (pw == "") {
alert("Password field is required");
return false;
}
if (pw.length < 6) {
alert("Password length must be atleast 6 characters");
return false
}
var validPass = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]$/
if (!pw.match(validPass)) {
alert("Password requires at least one capital and lowercase letter , one number, and one special character")
return false;
}
if (pwC == "") {
alert("Confirm Password field is required");
return false;
}
if (pw != pwC) {
alert("Passwords do not match");
return false;
} else {
return true;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="Assignment4.css">
</head>
<body>
<form name="form" onsubmit="return VerifyAndConfirmPassword()" method="post" action="mailto:jjohn#JJohnsonRE.ca">
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="txtFirst" maxlength="100" placeholder="Your First Name"><br><br>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="txtLast" maxlength="100" placeholder="Your Last Name"><br><br>
<label for="address">Address:</label><br>
<input type="text" name="txtAdd" maxlength="100" placeholder="Address"><br><br>
<label for="city">City:</label><br>
<input type="text" name="txtCity" maxlength="100" placeholder="City"><br><br>
<label for="postalCode">Postal Code:</label><br>
<input type="text" name="txtPC" maxlength="100" placeholder="Postal Code"><br><br>
<label for="province">Province: (Must use initials)</label><br>
<input type="text" id="txtPro" maxlength="100" placeholder="Province"><br><br>
<label for="age">Age:</label><br>
<input type="number" name="numAge" maxlength="100" placeholder="Age"><br><br>
<label for="password">Password:</label><br>
<input type="password" name="passPass" id="passPass" maxlength="100" placeholder="Password"><br><br>
<span id="message"></span>
<label for="Cpassword">Confirm Password:</label><br>
<input type="password" id="passCPass" name="passCPass" maxlength="100" placeholder="Password"><br><br>
<span id="messageC"></span>
<span id="confirm"></span>
<label>Your Email:</label><br>
<input name="txtEmail" type="text" maxlength="100" placeholder="Email"><br><br>
<input type="submit" value="Register Now">
<input type="reset" value="Clear Form">
</form>
<script src="Assignment4.js"></script>
</body>
</html>
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>
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>
for my nic input,the no. of characters should be equal to 14 which i already did and the first character should be equal to the first letter in Lastname. how am i suppose to put this validation.
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :<input type="text" name="lastname" id="lastname">
</input><br><br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[0-9]{14}" maxlength="14"></input></br></br>
<input id="submit" type="submit" name="submit" id="submit">
You can add a custom validation: JSFiddle
Code
function validateNIC() {
var nic = document.getElementById("NIC").value;
var lname = document.getElementById("lastName").value;
var valid = true;
if (nic.length != 14) {
console.log("Length must be 14 characters");
} else if (nic[0] != lname[0]) {
console.log("First Character of both input should be same");
}
else{
console.log("Valid")
}
}
<input type="text" id="lastName">
<input type="text" id="NIC" maxlength=14>
<button onclick="validateNIC()">validate</button>
try like this using charAt.
var x = 'some string';//value from first field
var y="s2324343353";//value from nic
if(x.charAt(0) == y.charAt(0)){
alert("first character is same");
}// alerts 's'
I have modified pattern to accept first character as alphanumeric. Then following function should help you validate the first character mismatch validation.
function formValidation() {
var ln = document.getElementById("lastname");
var nic = document.getElementById("NIC");
if (ln.value.substr(0, 1) != nic.value.substr(0, 1)) {
alert("NIC first character not acceptable.");
return false;
} else {
return true;
}
}
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :
<input type="text" name="lastname" id="lastname">
</input>
<br>
<br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[a-zA-Z0-9][0-9]{13}" maxlength="14"></input>
</br>
</br>
<input id="submit" type="submit" name="submit" id="submit">
function formValidation() {
var lastname = $('#lastname').val();
var NIC = $('#NIC').val();
if (lastname.charAt(0) != NIC.charAt(0)) {
return false;
}