Submitting form even when validation regex is wrong - javascript

i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>

You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>

Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>

Related

Validating multiple fields in a form - Javascript

I am trying to validate three fields within my form. I have written the code for them and thought they would work. The only problem I'm having is that they're not done in a sequence. If i submit the form without filling in anything, it picks up the email validation.If i fill in the first name, again skips the first name and surname validation and goes straight to email. I tried to make it work in a sequence so first name first then surname and email. Any help would be appreciated.
JS
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
}
function validateForm() {
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
}
function validateForm() {
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
HTML
<form name="buyProductForm" onsubmit="return validateForm()" method="post">
<fieldset id="field1">
<legend>Personal Details</legend>
<label for="name">Firstname:</label>
<input type="text" name="fname" placeholder="Enter your first name" ><br>
<label for="name">Surname:</label>
<input type="text" name="sname" placeholder="Enter your surname"><br>
<label for="email">Email Adress:</label>
<input type="email" name="email" placeholder="Enter your email" ><br>
Jsut create only one validateForm() function and inside this function validate all your fields.
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
<form name="buyProductForm" onsubmit="return validateForm()" method="post">
<fieldset id="field1">
<legend>Personal Details</legend>
<label for="name">Firstname:</label>
<input type="text" name="fname" placeholder="Enter your first name" ><br>
<label for="name">Surname:</label>
<input type="text" name="sname" placeholder="Enter your surname"><br>
<label for="email">Email Adress:</label>
<input type="email" name="email" placeholder="Enter your email" ><br>
<input type="submit" value="Submit">
</form>
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}

how can find Form Validations in JavaScript not work

<script>
function validate() {
var username = document.getElememtById("uname");
var password = document.getElememtById("pass");
if (username.value == "" || password.value == "") {
alert("no data");
}
}
</script>
<form>
<input id="uname" type="text" placeholder="username"></input>
<input id="pass" type="password" placeholder="password"></input>
<button onclick="validate()" type="submit">Submit</button>
</form>
Prevent the default behavior using e.preventDefault and also there is typo in getElememtById
function validate(e) {
e.preventDefault();
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value == "" || password.value == "") {
alert("no data");
}
}
<form>
<input id="uname" type="text" placeholder="username" />
<input id="pass" type="password" placeholder="password" />
<button button type='submit' onclick="validate(event)" type="submit">Submit</button>
</form>
There are a few issues on your code:
1) The input tag do not use a close tag like </input>
2) You need to pass event as the argument of your custom function and then call event.preventDefault() to prevent the default submit event associated with the form.
3) getElememtById() is actually named like getElementById()
Working example:
function validate(event)
{
event.preventDefault();
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value == "" || password.value == "")
{
alert("no data");
}
}
<form>
<input id="uname" type="text" placeholder="username">
<input id="pass" type="password" placeholder="password">
<button onclick="validate(event)" type="submit">Submit</button>
</form>
You have typo in getElememtById, should be getElementById. You also have to prevent the default event if condition is true.
Please Note: input is called empty or void element and only have a start tag since they can't have any content. Using closing tag in empty element is a bad parctice.
<script>
function validate(e) {
use
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value == "" || password.value == "") {
alert("no data");
e.preventDefault();
}
}
</script>
<form>
<input id="uname" type="text" placeholder="username"/>
<input id="pass" type="password" placeholder="password"/>
<button onclick="validate(event)" type="submit">Submit</button>
</form>

Encrypt Password

I have a login page having username and password after successful entry of username and password, it forward to the login controller.
My problem is that while forwarding to next page, in url the password enter is showing. I need to encrypt that and send over controller and have to decrypt that over controller.
this is my code.
jsp:
<form action="Login" onsubmit="return validate1()">
<h3>
<font color="red">username</font>
</h3>
<input type="text" name="username" id="username" /><br>
<h3>
<font color="red">password</font>
</h3>
<input type="password" name="password" id="password" /><br> <input type="submit" value="submit" />
</form>
javascript:
<script>
function validate1() {
return validate();
}
function validate() {
var isValid = true;
var name = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (name.length == 0) {
isValid = false;
alert("Username empty");
} else if (password.length == 0) {
isValid = false;
alert("Password empty");
}
return isValid;
}
</script>
url:
http://localhost:8080/PSMS/Login?username=jay&password=jay
here password is visible I need to encrypt the password and forward to controller where again I have to decrypt that password.
I think you need add an attribute to your form tag.
<form method="post"> ...

Submitting a PHP form with onClick

So I currently have a download link and an input field for an email address on my website.
In order to download the file you first need to put in your email.
I use a form to do this, with the email field being an input field and the download button being a submit button.
I like HTML5's form validation (the required fields, field types etc, it all looks very nice).
The problem is that if I use onClick in my submit button then none of the nice form validation works.
<form>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" class="btn" onclick="downloadWin()" value="Windows">
<input type="submit" class="btn" onclick="downloadOsx()" value="Osx">
</form>
<script>
function downloadWin(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadWin&email='+email;
}
}
}
function downloadOsx(){
event.preventDefault();
var email = $("#email").val();
if(email != ''){
if(validateEmail(email)){
location.href='http://s/index.php?page=downloadOsx&email='+email;
}
}
}
</script>
This might not be the cleanest way to do it, so please if you think you know a better way tell me :)
Try this:
<form onsubmit="download(this.email.value,this.system.value)" id="form">
<input type="email" id="email" name="email" placeholder="Please enter email" required>
<input type="radio" name="system" value="Win" required >Windows
<input type="radio" name="system" value="Osx" >Osx
<input type="submit" class="btn" value="Download">
</form>
<script type="text/javascript">
document.getElementById("form").addEventListener("submit", function(event){
event.preventDefault();
});
function download(email_value,sys_value){
location.href='http://s/index.php?page=download'+sys_value+'&email='+email_value;
}
</script>
Result:
try this code
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function downloadWin() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadWin&email=' + email;
}
}
return false;
}
function downloadOsx() {
var email = $("#email").val();
if (email != '') {
if (validateEmail(email)) {
location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
return false;
}
Below is the working code snippet (without using HTML5 validation). You can run and test it. I have used the jquery with jquery.validate plugin. You can uncomment the commented code to redirect user to the target url. Let us know if this what you are looking for or not. Feel free to comment if there is anything that you feel confusing.
$(document).ready(function(){
$(".btn-download").on("click", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if ($("#validateForm").valid()) {
var name = $(this).val();
var email = $("#email").val();
if (name === "Windows") {
//location.href = 'http://s/index.php?page=downloadWin&email=' + email;
console.log('http://s/index.php?page=downloadWin&email=' + email);
}
if (name === "Osx") {
console.log('http://s/index.php?page=downloadOsx&email=' + email);
//location.href = 'http://s/index.php?page=downloadOsx&email=' + email;
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<form method="post" action="" id="validateForm" novalidate>
<input type="email" id="email" placeholder="Please enter email" required>
<input type="submit" name="btnSubmit" class="btn btn-download" value="Windows">
<input type="submit" name="btnSubmit" class="btn btn-download" value="Osx">
</form>

Validate email field in the form while adding to the list

I am adding users to the list using pure js and I am trying to validate the email field using ajax. How to validate the email field before submitting the form? If the email field is valid then i want to submit or else I have show the error in valid email.
Here is the code
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
if you using js then below code will definitely help you.
if (document.getElementById('email').value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(document.getElementById('email').value) == true) {
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
edited code: u have to just replaced it with your code, hope will work for you:
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
Try This
HTML
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="email" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
JS
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
var emailPat = /^(\".*\"|[A-Za-z]\w*)#(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var EmailmatchArray = email.match(emailPat);
if (EmailmatchArray == null) {
email.focus(); }
else {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
}
return false;
}
DEMO HERE
Try this
It will validate the field , then add the info to list
<form id="myform" onsubmit="return addUser();">
<h2>Add a User:</h2>
<input id="username" type="text" required name="username" placeholder="name">
<input id="email" type="email" required name="email" placeholder="email">
<button type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
DEMO
For the simple validation use the following way (type="email")
<input id="email" type="email" name="email" placeholder="email">
Here is the w3schools link http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validate_email
For Depth use this :
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
//Your Code here
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</form>
Try this
function addUser() {
var email = document.getElementById('email').value;
var username =document.getElementById('username').value;
$.post('/url/to/validation/email/from/db', { "email": email, "username": username }, function(data) {
if(data && data.Success){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
document.getElementById('users').appendChild(entry);
}else{
alert('Email already exists!');
}
},'json');
return false;
}
This will validate the entered email against server and then adds to the list.

Categories