I want to use javascript to validate my form's input before sending the data to the php file. I tried using onSubmit, but for some reason the javascript function is getting skipped over and the data is going straight to the php file. I'm not sure what's wrong with my code- I'd initially put the javascript in another file, then I included it in the page itself with a <script> tag, it's still not working. Here's my code-
The form-
<form action="includes/register.inc.php" name="registration_form" method="post" onSubmit="return regform(this.form,
this.form.first-name, this.form.last-name, this.form.signup-username, this.form.signup-email,
this.form.signup-password, this.form.confirm-password);">
<input id="first-name" name="first-name" type="text" placeholder="First Name"/>
<input id="last-name" name="last-name" type="text" placeholder="Last Name"/>
<input id="signup-username" name="signup-username" type="text" placeholder="Username"/>
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail"/>
<input id="signup-password" name="signup-password" type="password" placeholder="Password"/>
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password"/>
<input type="submit" value="CREATE ACCOUNT"/>
</form>
Javascript-
function regform(form, fname, lname, uid, email, password, conf) {
// Check each field has a value
if (uid.value == '' ||
email.value == '' ||
password.value == '' ||
fname.value == '' ||
lname.value == '' ||
conf.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if(!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if(!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
it's not this.form, since this already refers to the form. also you need to use brackets for any properties that contain a hyphen as JS will think it's a minus sign. this['last-name']
Try this. Instead of pass a bunch of params to the function, I'm passing the form itself, then pulling out values from there.
function regform(form) {
// Check each field has a value
if (form['signup-username'].value == '' ||
form['signup-email'].value == '' ||
form['signup-password'].value == '' ||
form['first-name'].value == '' ||
form['last-name'].value == '' ||
form['confirm-password'].value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if (!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if (!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if (!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
<form action="" name="registration_form" method="post" onSubmit="return regform(this);">
<input id="first-name" name="first-name" type="text" placeholder="First Name" />
<input id="last-name" name="last-name" type="text" placeholder="Last Name" />
<input id="signup-username" name="signup-username" type="text" placeholder="Username" />
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail" />
<input id="signup-password" name="signup-password" type="password" placeholder="Password" />
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password" />
<input type="submit" value="CREATE ACCOUNT" />
</form>
Related
I am making a password validation using js and html. It suppose to show certain information under the input parts if the input is not valid. But whatever the input is, there's no message at all. I am not sure which part I did wrong. Code is posted below
var name = document.getElementById("userName");
var passWord = document.getElementById("passWord");
var flag;
function check() {
flag = validateInput(name, passWord);
if (flag)
isPaswordValid(passWord);
if (flag)
ispassWordStrong(passWord);
}
function validateInput(name, passWord) {
if (name.length = 0 || passWord.length < 0) {
document.getElementById("errorMessage").innerHTML = "Please enter Username and passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check Username and passWord are valid
function isPaswordValid(passWord) {
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
//Check passWord is valid or not and having length of passord should not less than 8
if (passWord.length < 8 || (!re.test(passWord))) {
document.getElementById("errorMessage").innerHTML = "Invalid passWord. Please enter new passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check password has no more than 3 characters from username in passWord
function ispassWordStrong(userName, passWord) {
var n = 0;
for (var i = 0; i < userName.length; i++) {
if (passWord.indexOf(userName[i]) >= 0) {
n += 1;
}
}
if (n > 3) {
document.getElementById("errorMessage").innerHTML = "passWord can't contain more than 3 characters from the username.";
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
}
}
});
<body>
<fieldset>
<legend>Password Validator</legend>
User Name:
<input type="text" id="userName" name="userName" placeholder="User Name" onkeyup='check();' /><br>
passWord:
<input type="password" id="passWord" name="passWord" placeholder="Password" onkeyup='check();' />
<input type="submit" id="inputValidate" value="Validate"><br /><br />
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
</body>
Sorry for the long codes and thanks for your help.
The following should do what you require:
// collect all DOM elements in object ti: ti.i, ti.e, ti.u, ti.p
const ti=["inputValidate","errorMessage","userName","passWord"]
.reduce((a,c)=>(a[c.substr(0,1)]=document.querySelector('#'+c),a),{});
// delegated event listening for event "input":
document.querySelector('fieldset').addEventListener('input',ev=>{
if (Object.values(ti).indexOf(ev.target)>1){ // for userName and passWord do ...
let u=ti.u.value.toLowerCase();
ti.e.textContent= (ti.p.value.length > 2
&& ti.p.value.split('').reduce((a,c)=>a+=u.indexOf(c.toLowerCase())>-1?1:0,0) > 2 )
? "The password contains at least 3 letters from the username!" : "";
}})
// event listening for button click on "validate":
ti.i.addEventListener('click',ev=>!(ti.e.textContent=
(ti.u.value.trim().length ? "" : "User name is empty.") ||
(ti.p.value.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)
? "" : "The password is not complex enough!" )))
<fieldset>
<legend>Password Validator</legend>
User Name:<br/>
<input type="text" id="userName" name="userName" placeholder="User Name"/><br>
passWord:<br/>
<input type="password" id="passWord" name="passWord" placeholder="Password"/>
<input type="submit" id="inputValidate" value="Validate"><br/>
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
While inputting characters in the fields #userName and #passWord it checks for the occurence of user name characters in the password. This is done ignoring upper or lower case. And when clicking on the "validate" button the complexity of the password is checked against the regular expression /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/. This regular expression demands at least
one upper case chraracter,
one lower case character
one number and
a minimum length of 8.
There is also a rudimentary check on the user name. It must contain at least one non-blank character. The event handler for the click event on the "validate" button returns false whenever an error is detected. This can be used to prevent the submission of the form. However, the form itself was not supplied by OP.
I have done a javascript form validation using the following code.I'm not sure whether it is the correct way of validating form.
const signup=()=>{
let name=document.querySelector("#u_name").value;
let email=document.querySelector("#email_id").value;
let password=document.querySelector("#pwd").value;
let confirmPassword=document.querySelector("#confirm_pwd").value;
let i=0;
if((name==""||email=="")||(password==""||confirmPassword==""))
{
document.querySelector("#empty-field").innerHTML="*Fill all required fields";
i++;
}
else
{
if(name.length<3)
{
document.querySelector("#u_name").style.borderColor="red";
document.querySelector("#user-errmsg").innerHTML="*Enter valid user name";
i++;
}
else
{
document.querySelector("#u_name").style.borderColor="#ced4da";
document.querySelector("#user-errmsg").innerHTML="";
i;
}
if(email.length<6)
{
document.querySelector("#email_id").style.borderColor="red";
document.querySelector("#email-errmsg").innerHTML="*Enter valid email id";
i++;
}
else
{
document.querySelector("#email_id").style.borderColor="#ced4da";
document.querySelector("#email-errmsg").innerHTML="";
i;
}
if(password.length<6 && confirmPassword.length<6)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length<6 && confirmPassword.length>=6)
{
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length>=6 && confirmPassword.length>=6)
{
if(password!= confirmPassword)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
else
{
document.querySelector("#pwd").style.borderColor="#ced4da";
document.querySelector("#confirm_pwd").style.borderColor="#ced4da";
document.querySelector("#pwd-errmsg").innerHTML="";
i;
}
}
else
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
document.querySelector("#empty-field").innerHTML="";
}
if(i==0)
return true;
else
return false
}
Is it a good practice to write too many if else condition? If not, how can I rewrite it?
//ignore
Looks like stackoverflow doesn't allow posting this question with less details :/ So I have to add some more it seems.
Your concern about using too many if/else statements during the scope of a single method is a valid one. It is not wrong, but makes the code hard to read/understand and difficult to debug/troubleshoot if something goes wrong. Here are some advices to refactor this method:
It seems that it isn't doing a signup. You're validating input data so I would recommend to rename it to validate or something similar.
Method is doing too much. It's querying for the data, it's performing validations and also rendering messages and adapting styles. I advice to divide and conquer. Make this method just a validation one.
Create small functions that performs a single validation. As an example validateEmailAddress() or validatePassword(). Once you start moving pieces around, you will have less if/elseif statements.
There are more things you can do but the key is on decoupling responsibilities. If you try that I believe your if/elseif amount will decrease.
There is another strategy that I use all the time to remove if/else nesting levels which is commonly called as early return.
Your code would benefit from extracting everything into functions:
const get = selector => document.querySelector(selector);
const checker = (check, msg) => (el, error) => {
if(check(get(el).value)){
get(el).style.color = "green";
get(error).innerHTML = "";
return true;
} else {
get(el).style.color = "red";
get(error).innerHTML = msg;
}
};
const minLength = length => checker(
v => v.length >= length,
`Too short! You need at least ${length} chars`
);
const maxLength = length => checker(
v => v.length <= length,
`Too long! You need less than ${length} chars`
);
const equal = (a, b, err) => checker(v => v === get(b).value, "They must be equal")(a, err);
Seems quite long right? But now you can do:
return (
minLength(6)("#u_name", "#user-errmsg") &&
maxLength(12)("#u_name", "#user-errmsg") &&
minLength(6)("#email_id", "#email-errmsg") &&
equal("#confirm_pwd", "#pwd", "#pwd-errmsg")
)
use jquery plugin https://jqueryvalidation.org/
Below is the example to use:
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "myform"
$("form[name='myform']").validate({
// Specify validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 8 characters long"
},
email: "Please enter a valid email"
},
submitHandler: function(form) {
form.submit();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<div>
<h2>Sign Up</h2>
<form action="" name="myform">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="Robert" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" placeholder="Smith" />
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="name#company.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="" />
<button type="submit">Submit</button>
</form>
</div>
CSS to highlight error
label.error {
color: red;
margin-top:-10px;
margin-bottom:15px;
}
You don't need any javascript validation or extra library, just use all the attributes that is needed on the fields and correct type. use "constraint validation". Only thing you need to check is if the password match (showing you how below)
Study the input attributes here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
function validatePassword(){
const pwd1 = document.getElementById("pwd")
const pwd2 = document.getElementById("confirm_pwd")
pwd1.setCustomValidity(pwd1.value !== pwd2.value
? "Passwords Don't Match"
: ""
)
}
document.getElementById("pwd").oninput = validatePassword
document.getElementById("confirm_pwd").oninput = validatePassword
input:not([type=submit]):valid {
border: 1px solid lime;
}
<form class="" action="index.html" method="post">
<br>name<br>
<input name="" required type="text" autocomplete="name" minlength="3" id="u_name">
<br>email<br>
<input name="" required type="email" autocomplete="email" id="email_id">
<br>pwd<br>
<input name="" required type="password" autocomplete="new-password" minlength="6" id="pwd">
<br>repeat pwd<br>
<input name="" required type="password" autocomplete="new-password" minlength="6" id="confirm_pwd">
<br><input type="submit">
</form>
Personally I feel very tired off repeating my email and/or password. If i get it wrong i will do it over again or press that "forgot your password" link. I can see my email address and with the help of autocomplete it's a lower risk i get my email wrong. You don't need that b/c every other website dose it. if that is out of the way you don't need any javascript at all...
There are similar questions, but I can't find the way I want to check the form submit data.
I like to check the form submit data for phone number and email. I check as follows, but it doesn't work.
How can I make it correct?
<script>
function validateForm() {
var x = document.forms["registerForm"]["Email"].value;
if (x == null || x == "") {
alert("Email number must be filled out.");
return false;
}
else if(!/#./.test(x)) {
alert("Email number must be in correct format.");
return false;
}
x = document.forms["registerForm"]["Phone"].value;
if (x == null || x == "" ) {
alert("Phone number must be filled out.");
return false;
}
else if(!/[0-9]+()-/.test(x)) {
alert("Phone number must be in correct format.");
return false;
}
}
</script>
For email I'd like to check only "#" and "." are included in the email address.
For phone number, I'd like to check ()-+[0-9] and one space are only accepted for phone number, for example +95 9023222, +95-1-09098098, (95) 902321. How can I check it?
There will be another check at the server, so there isn't any need to check in detail at form submit.
Email validation
From http://www.w3resource.com/javascript/form/email-validation.php
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
Phone number validation
From http://www.w3resource.com/javascript/form/phone-no-validation.php.
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if ((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You can do something like this:
HTML part
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" placeholder="Email*" name="email" id="email" />
<div id="email-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
<div class="form_box">
<div class="input_box ">
<input maxlength="10" type="text" placeholder="Phone*" name="phone" id="phone" />
<div id="phone-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
Your script
var email = $('#email').val();
var phone = $('#phone').val();
var email_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,3}))$/;
var mobile_re = /^[0-9]{10}$/g;
if ($.trim(email) == '') {
$('#email').val('');
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter your Email');
} else if (!email.match(email_re)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter valid Email');
}
if ($.trim(phone) == '') {
$('#phone').val('');
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter your Phone Number');
} else if (!phone.match(mobile_re)) {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter valid Phone Number');
} else {
$('#phone-error').css('display', 'none');
$('#phone-error').html('');
}
You could of course write the validation part yourself, but you could also use one of the many validation libraries.
One widely used one is Parsley. It's very easy to use. Just include the .js and .css and add some information to the form and its elements like this (fiddle):
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>
<form data-parsley-validate>
<input data-parsley-type="email" name="email"/>
</form>
HTML5 has an email validation facility. You can check if you are using HTML5:
<form>
<input type="email" placeholder="me#example.com">
<input type="submit">
</form>
Also, for another option, you can check this example.
The code I have for my username and password verification is bringing up an error and im not sure how to fix it
I am trying to use
function checkForm(form) {
if (form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if (!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false.pwd2.value) {
if (form.pwd1.value.length < 8) {;
}
if (form.pwd1.value != "" && form.pwd1.value == form alert("Error: Password must contain at least eight characters!"); form.pwd1.focus();
return false;
}
if (form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if (!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if (!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if (!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
I am trying to use this code for this html
<form name="hw4Form" action="" autocomplete="off">
<br>
<fieldset name="LoginInfo">
<input id="username" type="text" name="username" placeholder="username" size="30">
<br>
<br>
Password:
<br>
<input id="pwd1" type="password" name="pwd1" placeholder="password" required="required" size="30">
<span id="pwd1Hint" class="hint">Password is too short (must be at least 8 characters)</span>
<br>
Repeat Password:
<br>
<input id="pwd2" type="password" name="pwd2" placeholder="password" required="required" size="30">
<span id="pwd2Hint" class="hint">Passwords don't match</span>
<br>
<br>
I get a error in my code editing software but I cant figure out how to fix it
I also would just like to make sure that this javascript will work for the html
Looks like this line:
if(form.pwd1.value != "" && form.pwd1.value == form
should be:
if(form.pwd1.value != "" && form.pwd1.value == form.username.value)) {
or something similar to this.
In your html you also need to close your form with </form>
I advice u using console.log(form) or other fields to check the js performing process.Or why not use firebug to debug the function.
I do not know why it is telling me always that is an invalid email address even when it is correct.Any ideas? Demo on JSfiddle
my form
<form id="FormViewForm" method="post" action="/NewsletterMailer/subscribe/4" accept-charset="utf-8">
<input type="hidden" name="_method" value="POST" />
<input type="hidden" name="data[Form][id]" value="4" id="FormId" />
<input type="hidden" name="data[Form][type]" value="1" id="FormType" />
<input type="email" name="data[Form][e-mail]" value="" id="subscribe-email" placeholder="Enter your email..." required>
<input type="submit" value="+" class="large" id="subscribe-submit">
</form>
my custom.js
$('#FormViewForm').submit(function() {
validateEmail($('input').val());
return false;
});
function validateEmail(email) {
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#c-e.com', email.length - '#c-e.com'.length) !== -1) {
alert('Submission was successful.');
} else {
alert('Email must be a CE e-mail address (your.name#c-e.com).');
}
} else {
alert('Not a valid e-mail address.');
}
}
Simply a jQuery selector issue, you're missing a #.
validateEmail($('#subscribe-email').val());
Your function receives undefined as an e-mail and the regex fails.
You could also use pure JavaScript. (Note that document.getElementById does not require the #, which might have caused the confusion.)
validateEmail(document.getElementById('subscribe-email').value);
Please use right selector like
If you want to user id as selector
validateEmail($('#subscribe-email').val());
Or you can also use input tag as selector
validateEmail($('input[type=email]').val());
The id selector will be strong to all browser and also safe to use
Please try this code
$('#FormViewForm').submit(function() {
validateEmail($('#subscribe-email').val());
return false;
});
function validateEmail(email) {
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#c-e.com', email.length - '#c-e.com'.length) !== -1) {
alert('Submission was successful.');
} else {
alert('Email must be a CE e-mail address (your.name#c-e.com).');
}
} else {
alert('Not a valid e-mail address.');
}
}