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>
Related
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 do client-side validation using javascript and all the things are working properly, only it doesn't redirect to another page -> redirect.html
After clicking on the alert pop-up it again loads the index.html.
document.getElementById('sub-btn').addEventListener('click', function() {
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"></meta>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Sign Up</title>
</head>
<body>
<div class="main">
<div class="form-box">
<form class="input">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>
</div>
</div>
</body>
<script src="script.js" type="text/javascript"></script>
</html>
Referring the link button type submit/button
document.getElementById('sub-btn').addEventListener('click', function() {
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"></meta>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Sign Up</title>
</head>
<body>
<div class="main">
<div class="form-box">
<form class="input">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="button">SIGN UP</button>
</form>
</div>
</div>
</body>
<script src="script.js" type="text/javascript"></script>
</html>
you need to add event preventdefault I think
document.getElementById('sub-btn').addEventListener('click', function(e) {
e.preventDefault()
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
form already has a built in redirect functionality by using the attribute action which also provides the benefit of actually posting the data to the desired link, if required.
Furthermore form has an event onsubmit which gets executed before submitting the form and can be cancelled by returning false.
Since all the mentioned requirements for your code are already given by the default behaviour of form, there is less reason not to use it.
Here is what you would need to change:
Instead of defining a click event, you define a standalone validation
function (=myValidator()), which returns true once all criterias are fulfilled and
false until. This better good practise anyway, since you can call it
independent of click events.
Setting the actionof the form to the desired URL (=redirect.html)
Forward the return of myValidator() to the onsubmit event on the form
function myValidator(){
//REM: returns true once valid, false until.
var tReturn = true;
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
tReturn = false
}else if (lastName.length === 0) {
alert('Enter the last name!');
tReturn = false
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
tReturn = false
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
tReturn = false
}else if (phoneNum.length > 10) {
alert('Check phone number!');
tReturn = false
}else if (emailID.length === 0) {
alert('Enter the email ID !');
tReturn = false
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
tReturn = false
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
tReturn = false
};
return tReturn
}
<!--REM: It is better practise to assign those events using javascript - I merely leave it here to point put the event/difference -->
<form class="input" action="redirect.html" onsubmit="return myValidator()">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>
Also note that empty inputs can nowadays be prevented by using the attribute required as well as other nice form-features and be styled accordingly using pseudo-css-classes.
<form class="input" action="redirect.html">
<input class="input-field" id="fname" placeholder="First Name" type="text" required>
<input class="input-field" id="lname" placeholder="Last Name" type="text" required>
<input class="input-field" id="dob" placeholder="Date of Birth" type="date" required>
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text" required>
<input class="input-field" id="email" placeholder="Email ID" type="email" required>
<input class="input-field" id="password" placeholder="Enter Password" type="password" required>
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password" required>
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</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>
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
I'm trying to use javascript to perform client-side verification of input to the following form. The 'firstname' field should contain only alphabetical characters. How can I write the validation function to implement this behaviour?
form.html
<html>
<head>
<script type="text/javascript" src="mainform.js"></script>
</head>
<body>
<form name="mainform" method="post" onSubmit="return validation();" >
firstname <input type="text" name="firstname"><br>
lastname <input type="text" name="lastname"><br>
username <input type="text" name="username"><br>
password <input type="password" name="password"><br>
confirm password<input type="password" name="cpassword"><br>
email <input type="email" name="email"><br>
phone no <input type="text" name="phoneno"><br>
<input type="submit" name="submit">
</body>
</html>
form.js
function validation()
{
var fname=document.mainform.firstname;
var letters="/[a-zA-Z]$/";
if(fname.value.match(letters)){
return true;
}
else
{
alert('first name must be alphabets');
fname.focus();
return false;
}
}
function validation()
{
var fname = document.mainform.firstname;
if(/^[a-zA-Z]+$/.test(fname.value)) {
return true;
} else {
alert('first name must be alphabets');
fname.focus();
return false;
}
}
Do not forget to make a check on the server side too for security.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hide</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<style type="text/css">
label input[type="button"]
{
background: #E17698;
}
</style>
<script>
$(document).delegate("#submit","click",function(e)
{
var name = $("#fname").val();
var hasError = false;
var searchReg = /^[a-zA-Z ]+$/;
if(name == '') {
$("#txtt").after('<span class="error" style="color:red;"> *Fill Name Box</span>');
hasError = true;
} else if(!searchReg.test(name)) {
$("#txtt").after('<span class="error" style="color:red;"> **Enter Vaild Name.</span>');
hasError = true;
}else if(searchReg.test(name)) {
$("#txtt").after('<span class="error" style="color:white;"> Vaild Name</span>');
}
if(hasError == true) {
return false
}
});
</script>
</head>
<body>
<form name="mainform" method="post">
firstname <input type="text" name="firstname" id='fname'><label id="txtt"></label><br>
lastname <input type="text" name="lastname"><br>
username <input type="text" name="username"><br>
password <input type="password" name="password"><br>
confirm password<input type="password" name="cpassword"><br>
email <input type="email" name="email"><br>
phone no <input type="text" name="phoneno"><br>
<input type="submit" name="submit" id='submit'>
</form>
</body>
</html>