I want to make a form validation using JavaScript but its not working properly. Can someone please help me?
here is my code:
JavaScript
<script type="text/javascript">
var ck_name = /^[A-z]+$/;
var ck_email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate()
{
var name = document.form.name;
var email = document.form.email;
var username = document.form.username;
var password = document.form.password;
if (!ck_name.test(name)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
</script>
HTML
<form action="#" name="form" onsubmit="return validate();">
<p>Name: <input type="text" size="25" name="name"/></p>
<p>E-mail: <input type="text" size="25" name="email"/></p>
<p>UserName: <input type="text" size="25" name="username"/></p>
<p>Password: <input type="text" size="25" name="password"/></p>
<p><input type="submit" value="Send" name="submit" />
<input type="reset" value="Reset" name="reset" /></p>
</form>
You need to get form from document here is what you should use
var name = document.forms[0].name.value;
var email = document.forms[0].email.value;
var username = document.forms[0].username.value;
var password = document.forms[0].password.value;
This will only get html element
var name=document.forms[0].name
You need to get its value.
var name=document.forms[0].name.value;
Update the js code to get the element value
var name = document.forms['form'].elements['name'].value;
var email = document.forms['form'].elements['email'].value;
var username = document.forms['form'].elements['username'].value;
var password = document.forms['form'].elements['password'].value;
You are checking input elements instead you need to check their value.
Here is the updated/working code.
function validate() {
var name = document.form.name;
var email = document.form.email;
var username = document.form.username;
var password = document.form.password;
if (!ck_name.test(name.value)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email.value)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username.value)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password.value)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
You should get elements' value. I just made some changes and works properly. Try this:
var ck_name = /^[A-z]+$/;
var ck_email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate() {
var name = document.form.name.value;
var email = document.form.email.value;
var username = document.form.username.value;
var password = document.form.password.value;
if (!ck_name.test(name)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
<form action="#" name="form" onsubmit="return validate();">
<p>Name:
<input type="text" size="25" name="name" />
</p>
<p>E-mail:
<input type="text" size="25" name="email" />
</p>
<p>UserName:
<input type="text" size="25" name="username" />
</p>
<p>Password:
<input type="text" size="25" name="password" />
</p>
<p>
<input type="submit" value="Send" name="submit" />
<input type="reset" value="Reset" name="reset" />
</p>
</form>
Related
My javascript isn't running when I click submit on my form page.
<form onsubmit="validateReg()">
<p>
//email registration
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
//password registration
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</for
I've tried multiple times linking the Javascript to the Html form and on the page when I click submit it doesn't return any of my error alerts.
//HTML
<form onsubmit="validateReg()">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
//Javascript
//Main Function
function validateReg(){
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.value.match(lowerCaseLetters)) {
return true;
}else{
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.value.match(upperCaseLetters)){
return true;
}else{
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.value.match(numbers)){
return true;
}else{
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.value.match(special)){
return true;
}else{
alert("Password needs a special character!");
return false;
}
if(password.value.length >=8){
return true;
}else{ alert("Password needs to be at least 8 characters");
return false;
}
}
I expect the code to output errors when a password is incorrectly submitted and when a password and email is correctly submitted so out put thank you.
As Oluwafemi put it you could put an event listener on your 'submit' event instead. I would put the event on the submit button though. That way you can stop it on the click event without having to fire the submit of the form. If you update your code it could help with troubleshooting in the future.
It wouldn't take much to modify your code either.
First, you would need to update your form to look like this:
<form id="form">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p>
<p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br />
<input id="submitButton" type="submit" class="submit">
</form>
Then add this below your javascript function like so:
document.querySelector("#submitButton").addEventListener("click", function(event) {
event.preventDefault;
validateReg()
}, false);
What this is doing is stopping the submit of the form and doing the check as expected. You can read more on this on the Mozilla developer site.
You will need to add document.getElementById('form').submit(); to any return statement that was set to true.
I did however, update the code to have the submit become the default functionality and the checks just return false if they fail like this:
//Javascript
//Main Function
function validateReg() {
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.match(lowerCaseLetters) == null) {
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.match(upperCaseLetters) == null){
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.match(numbers) == null){
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.match(special) == null){
alert("Password needs a special character!");
return false;
}
if(password.length < 8){
return false;
}
document.getElementById('form').submit();
}
A better way to do this is to add an event listener to your js file and listen for the 'submit' event. Followed by your function.
Furthermore ensure that your js file is added to your script tag in your HTML file. That should work if your logic is correct.
I am working on a mvc 5 project .in contact us page I want user to send admin his / her emaiul address .so I want to validate email in javascript on that page .I wrote some code that does not work properly. I want you to help me plesae.
<script language="javascript">
function f1() {
var inputText = document.getElementById("email").value;
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.value.match(mailformat)) {
document.form1.text1.focus();
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
<form name="form" action="#" onSubmit="return f1()" method="POST">
<input type="email">
</form>
<script>
function f1(){
var email = document.forms["form"]["Email"].value;
var regex = /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)#([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/;
if(!regex.test(email)){
alert("You have entered an invalid email address!");
return false;
}
}
</script>
You don't want inputText.value only inputText like this
<input type="text" id="email" />
<input type="submit" onClick="f1()"/>
<script language="javascript">
function f1() {
console.log(document.getElementById("email").value);
var inputText = document.getElementById("email").value;
console.log(inputText)
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.match(mailformat)) { // <<<<<<< here
//document.form1.text1.focus();
alert("correct")
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
A basic HTML and JS working code for validating email with JS is given here for u-
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;
}
else
{
alert("Valid e-mail address");
return true;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
Think, u have your answer :)
function validateEmail(email) {
var re = ([\w-+]+(?:\.[\w-+]+)*#(?:[\w-]+\.)+[a-zA-Z]{2,7});
return re.test(email);
}
I've read many posts considering this problem and for some reason none of the solutions work for me. I have several js functions for validation that are called in the main one that is appointed to the onSubmit tag in the form. Here is the js code:
<script type="text/javascript">
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
return true;
}
return false;
}
</script>
<script type="text/javascript">
function validacijaSifri(fieldId1, fieldId2)
{
var two = document.getElementById(fieldId1).value;
var three = document.getElementById(fieldId2).value;
if(two == three) { return true; }
alert("Warning!! passcodes must match!!!");
return false;
}
</script>
<script type="text/javascript">
function validacijaUsername(usname)
{
var letters = /^[A-Za-z]+$/;
if(letters.test(usname.value))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
document.getElementById('usrname').focus();
return false;
}
}
</script>
<script type="text/javascript">
function validacijaEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mailformat.test(email))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
document.getElementById(email).focus();
return false;
}
}
and here is the html form code
<form class="form-signin" onSubmit="return validacijaForme();" name="registerForm" method = "POST" action="test.php" enctype="multipart/form-data">
<h2 class="form-signin-heading">Registracija</h2>
<input type="text" class="form-control" placeholder="Username" name="usrname" id="usname" autofocus>
<input type="text" class="form-control" placeholder="E-mail" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass1">
<input type="password" class="form-control" placeholder="Confirm password" id="pass2">
<button class="btn btn-lg btn-primary btn-block" name="dugme" type="submit">Register</button>
The problem is that all the alerts are working, meaning that those functions do validate the fields, and should return false, but the onSubmit tag doesn't seem to accept that value from the function.
The form doesn't submit and doesn't pass to test.php only if I type this:
<form class="form-signin" onSubmit="return false" name="registerForm" method = "POST" action="test.php" enctype="multipart/form-data">
submit the form with javascript submit()
<form id="myform" class="form-signin" onSubmit="validacijaForme();" name="registerForm"
method = "POST" action="test.php" enctype="multipart/form-data">
And in your function:
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
document.getElementById("myform").submit();
return false;
}
return false;
}
Your problem is related to your username id/name consistency. Use the console (F12) to debug this kind of thing.
<input type="text" class="form-control" placeholder="Username" name="usRname" id="usname" autofocus>
Change:
document.getElementById('usrname').focus();
To:
document.getElementById('usname').focus();
There are lots of errors in your code buddy | WORKING DEMO
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
return true;
}
return false;
}
function validacijaSifri(fieldId1, fieldId2)
{
var two = fieldId1.value;
var three = fieldId2.value;
if(two == three) { return true; }
alert("Warning!! passcodes must match!!!");
return false;
}
function validacijaUsername(usname)
{
var letters = /^[A-Za-z]+$/;
if(letters.test(usname.value))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
document.getElementById('usname').focus();
return false;
}
}
function validacijaEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mailformat.test(email.value))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
document.getElementById('email').focus();
return false;
}
}
I am trying to create a very very basic profile page using Name, Email, Username, and Password. I have to have a password validation code/button.
The home page will be very similar to a common profile page. The user must be able to input the following:
Name field
Email field
User ID field
Password field 3
Validation Password field
The following buttons are required:
Password validation button
Create Profile button
I can put it all together, but the problem I am having is that the javascript console is telling me that there are some errors in the code...
function validate(){
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('Password2');
if (pass1 == pass2)
{
alert("Passwords Match")
}
else
{
alert("Passwords Do Not Match")
}
}
<head>
<script type="text/javascript" src="Profile Page.js"></script>
</head>
<body>
Enter First and Last Name
<input type="text" id="name">
<br>Enter Your Email Address
<input type="text" id="email">
<br>Please Enter a Username
<input type="text" id="username">
<br>Please Enter a Password
<input type="password" id="password">
<br>Enter Your Password Again
<input type="Password" id="password2">
<br>
<button type="button" id="validate" onClick="validate()">Validate Password</button>
<button type="button" id="create" onClick="submit()">Create Profile</button>
</body>
Ok, so I figured out where my errors were, now the alert that I set up for the passwords not matching is coming up, even when the passwords are the same thing. Any suggestions?
Please try it like this:
function validateForm(){
var pass1 = document.getElementsByName("password")[0].value;
var pass2 = document.getElementsByName("password2")[0].value;
if (pass1 === pass2) {
alert("Passwords Match");
} else {
alert("Passwords Do Not Match");
}
}
Enter First and Last Name
<input type = "text" id = "name" /><br/>
Enter Your Email Address
<input type = "text" id = "email" /><br/>
Please Enter a Username
<input type = "text" id = "username" /><br/>
Please Enter a Password
<input type = "password" name = "password" /><br/>
Enter Your Password Again
<input type = "Password" name= "password2" /><br/>
<button type = "button" id = "validate" onclick = "validateForm();">Validate Password</button>
<button type = "button" id = "create" onclick = "submit()">Create Profile</button>
Below is the generic function to validate password by comparing with repeat password, Contains lowercase, Contains uppercase, Contains digit
function validatePassword(password, repeatPassword){
var MinLength = 6;
var MaxLength = 15;
var meetsLengthRequirements:boolean = password.length >= MinLength && repeatPassword.length <= MaxLength;
var hasUpperCasevarter:boolean = false;
var hasLowerCasevarter:boolean = false;
var hasDecimalDigit:boolean = false;
if (meetsLengthRequirements)
{
for (var i = 0, len = password.length; i < len; i++) {
var char = password.charAt(i);
if (!isNaN( +char * 1)){
hasDecimalDigit = true;
}
else{
if (char == char.toUpperCase()) {
hasUpperCasevarter = true;
}
if (char == char.toLowerCase()){
hasLowerCasevarter = true;
}
}
}
}
var isValid = meetsLengthRequirements
&& hasUpperCasevarter
&& hasLowerCasevarter
&& hasDecimalDigit;
return isValid;
}
Below is form validation using JavaScript but it's not working.
function validate()
{
var n=document.frm.name.value();
if(!n.match(/^[a-zA-Z]+$/))
{
alert("Enter valid Name");
document.frm.name.value="";
document.frm.name.focus();
return false;
}
var b=document.frm.mob.value();
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
return false;
}
var y=document.frm.nn.value();
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
return false;
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
return false;
}
}
<body>
<form name="frm" action="#" method="post" onsubmit="return validate()">
Name :<input type="text" name="name"/>
Mobile No:<input type="text" name="mob" />
Not Null :<input type="text" name="nn"/>
Email Id:<input type="text" name="email"/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
First off, don't name your fields with reserved words (like "name")
Second, value is a property, not a method, so,
var b=document.frm.mob.value;
(without the brackets)
Please,place return false outside the function.
var b=document.frm.mob.value;
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
}
var y=document.frm.nn.value;
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
}
return false;
}
Instead of calling the function validate() in form tag on event onsubmit, better use it in submit button
<input type="submit" name="submit" value="submit" onClick="return validate()" />
It will work better and outputs as required.