I am trying to do javascript form validation, and to do this I need to call two functions. One for the password and on for the username (I will also need to call more later on).
Here is my JS code:
function validateUserName(NewUser)
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
alert("You left Username field empty");
return false;
}
else if (uLength <4 || uLength > 11)
{
alert("The Username must be between 4 and 11 characters");
return fasle;
}
else if (illegalChars.test(u))
{
alert("The username contains illegal characters");
return false;
}
else
{
return true;
}
}
function validatePassword(pwd, confirmPwd)
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["cP"].value
var pLength = p.length;
if (p == null || p == "")
{
alert("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
alert("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
alert("Th passwords do not match!");
return false;
}
}
and here is my HTML form:
<form name = "NewUser" onsubmit= "return validateUserName(), return validatePassword()" action = "">
<tr>
<td>Username:</td>
<td><input type = "text" name = "user"/></td>
</tr>
<tr>
<td class = "Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
</tr>
<tr>
<td>Password:</td>
<td><input type = "password" name = "pwd"/></td>
<tr>
<td class = "Information"><em>6-20 characters</em></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type = "password" name = "confirmPwd"/></td>
<tr>
<td class = "Information"><em>just in case you didn't make mistakes!</em></td>
</tr>
<input type = "submit" value = "Submit"/>
Please ignore the table code.
Should I rather just put it all in one function? Or is there a way to call two functions at once?
You have multiple ways of approaching this, the easiest for your current set up would be:
combined function
The following will run both functions no matter what state is returned each time, because they are not executed inline as part of a logical expression which will "short circuit" when getting a false value:
function validateForm(){
var validation = true;
validation &= validateUserName();
validation &= validatePassword();
return validation;
}
And then in your form markup:
<form onsubmit="return validateForm()">
If would probably be advisable, in the interests of making more reusable code, to modify your validation functions so that they accept a form argument. This would mean you could do the following:
<form onsubmit="return validateForm(this);">
.. and have your receiving function do the following:
function validateForm(form){
var validation = true;
validation &= validateUserName(form);
validation &= validatePassword(form);
return validation;
}
add multiple events
You could also implement this via the preferred way of applying event listeners which is to use addEventListener instead of the html attribute onsubmit:
/// wait for window load readiness
window.addEventListener('load', function(){
/// you could improve the way you target your form, this is just a quick eg.
var form;
form = document.getElementsByTagName('form')[0];
form.addEventListener('submit', validateUserName);
form.addEventListener('submit', validatePassword);
});
The above assumes that it's required to support modern browsers. If you wish to support older versions of internet explorer you'd be better off making a function to apply your event handling e.g:
function addEventListener( elm, evname, callback ){
if ( elm.addEventListener ) {
elm.addEventListener(evname, callback);
}
else if ( elm.attachEvent ) {
elm.attachEvent('on'+evname, callback);
}
}
This second option makes it harder to exert a global control over what gets validated, where, when and in what order, so I'd recommend the first option. However I'd would also recommend at least applying your singular submit handler using the JavaScript method above, rather than using onsubmit="".
Simply combine the two with the logical AND operator:
<form name="NewUser" onsubmit="return validateUserName() && validatePassword();" action="">
<tr>
<td>Username:</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td class="Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd"/></td>
<tr>
<td class="Information"><em>6-20 characters</em></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirmPwd"/></td>
</tr>
<tr>
<td class="Information"><em>just in case you didn't make mistakes!</em></td>
</tr>
<input type="submit" value="Submit"/>
</form>
There are a few approaches to this. One is to create a function, such as submitForm() which then calls your two other functions. Perhaps using those function calls as part of if statements to provide client side validation.
The other method is to override the default submit functionality of the form, and instead call the functions as you see fit. jQuery provides an easy approach for this. Have a look at http://api.jquery.com/submit/ for more information.
Ideally, the validateUser() and validatePassword() functions would be merged into the one function validateUser(). You may want to provide the code of your current functions for advice on how to do that, if you're stuck...
Hope this helps :)
Why you are creating two different functions to validate both username and passwords, by the way you can go with this too like below:
Create Another third Function in which these two have to call and check if both returns true then return true otherwise its shows message or whatever you want to do.
Here is the code by which you can do it:
function validateUserName(NewUser) {
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "") {
alert("You left Username field empty");
return false;
}
else if (uLength < 4 || uLength > 11) {
alert("The Username must be between 4 and 11 characters");
return fasle;
}
else if (illegalChars.test(u)) {
alert("The username contains illegal characters");
return false;
}
else {
return true;
}
}
function validatePassword(pwd, confirmPwd) {
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["cP"].value
var pLength = p.length;
if (p == null || p == "") {
alert("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20) {
alert("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP) {
alert("Th passwords do not match!");
return false;
}
}
function finalvalidate() {
var newuser = $('[id$=newuser]').val();
var usernameresult = validateUserName(newuser);
var pwd = $('[id$=pwd]').val();
var confirmPwd = $('[id$=confirmPwd]').val();
var pwdresult = validatePassword(pwd, confirmPwd);
if (usernameresult == true && pwdresult == true) {
return true;
} else {
return false;
}
}
Hope this will work for you..
Create one function to call all your validators:
function validate() {
return validateUserName() && validatePassword();
}
HTML
<form name="NewUser" onsubmit="return validate()" action="">
Also in your password validation function you refer to incorrect field name.
Fixed code: http://jsfiddle.net/6sB29/
If you want to alert all the errors (not only the first) you can try something like this:
function validate() {
var name = validateUserName(),
pass = validatePassword();
return name && pass;
}
http://jsfiddle.net/6sB29/1/
try this
onsubmit="return fun2() && fun3();"
Related
Hollo All,
I am creating a form that exports data on submit to an ecommerce solution called Foxycart. I would like the form to only proceed onto foxycart when the date field is entered however it currently only displays the alert message then proceeds to the action on the form. Does anyone have advice on how to prevent the action on submit? please see code below:
<script>
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
}
}
</script>
<form name="delivery-date-info" action="https://austin-roman.foxycart.com/cart" method="post" accept-charset="utf-8" onsubmit="return validateForm()">
<div class="add-to-bag">
<label for="datepicker-example3"></label>
<input id="datepicker-example3" type="text" name="Delivery_Date_is">
<input type="submit" id="datepicker-example3" type="text" class="button-add">
</div>
</form>
Assuming you're using FoxyCart's default "sidecart" approach (as of v2.0), you'll need to use FoxyCart's own event system, described here. For your specific example, it might look like this:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
if (validateForm()) {
next();
}
});
};
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
} else {
return true;
}
}
Here's an alternate approach that'd be a bit more flexible, would allow more than one product form per page, and also shows a little more what's going on:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
$element = $(params.element);
if (
$element.attr('name') == 'delivery-date-info'
&& $element.find('[name="Delivery_Date_is"]').length > 0
&& !$element.find('[name="Delivery_Date_is"]').val()
) {
alert('Date must be filled out');
} else {
next();
}
});
};
I was adding some JavaScript validation to my page and found that I couldn't find any helpful sources to tell me on how to stop numerical values and allow them on different input boxes. I am very new to JavaScript and aren't quite up to grips with it yet. I know VB has a command similar to what I am asking for: isNumeric()
Here is the code what I want to stop numerical values in:
if (document.ExamEntry.name.value=="") {
alert("You must enter your name \n");
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
alert("You must enter the subject \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
Here is the code that I want to ONLY allow numerical values in:
if (document.ExamEntry.CadNumber.value.length!== 4) {
alert("Make sure you only have 4 numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
---EDIT---
Here is what I have got so far now, it works sort of however it contstantly appears now... I was wondering if you knew anymore?
Stop Numerical values:
if (document.ExamEntry.subject.value) {
isNaN(parseInt(1));
alert("Please make sure you only have letters! \n");
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
ONLY allow numerical values:
if (document.ExamEntry.CadNumber.value) {
isNaN(parseInt(""));
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
Look up isNaN and parseInt - they should get you started. From the JS console,
isNaN(parseInt("foo"))
true
isNaN(parseInt(12))
false
isNaN is like the opposite of your VBA isNumeric so you need to use it with parseInt on the document.ExamEntry.CadNumber.value
Use it like this:
if (isNaN(parseInt(document.ExamEntry.CadNumber.value))) {
alert("Please make sure you only have numbers! \n");
document.ExamEntry.CadNumber.focus();
document.getElementById('CadNumber').style.color="red";
result = false;
}
To give a small example of how it could work, you could check this small snippet.
In a sense, at the moment you submit your form, it will go to the validate function, that will then check your form for the requirements.
The numbers only / text only is implied by the type (and your browser can also help), and the error message is supplied in a title.
When one field fails, the validation stops and throws the error.
Note, if you have any other elements you want to check (like selects) you would have to do some extra work still ;)
And if you want to learn more about the element types you could set, you could check it here as well
function validate(form) {
var succeeded = true,
i, len, item, itemArray, firstErrorField;
if (!form) {
succeeded = false;
} else {
itemArray = form.getElementsByTagName('input');
for (i = 0, len = itemArray.length; i < len && succeeded; i++) {
item = itemArray[i];
switch (item.type) {
case 'text':
if ((!item.value && item.required) || !isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
case 'number':
if ((!item.value && item.required) || isNaN(parseInt(item.value))) {
succeeded = false;
}
break;
}
if (!succeeded) {
firstErrorField = item.title || item.id || item.name;
}
}
}
if (!succeeded) {
alert('please check your input!\r\n' + firstErrorField);
}
return succeeded;
}
<form onsubmit="return validate(this);">
<fieldset>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name" title="name is required" required />
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" id="age" required="required" min="0" title="age is required" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</fieldset>
</form>
I am validating a form which has validations for required field, character, number, email, password format, length of a field.
In my code, required field and length are working but the rest.
JavaScript code for Password format:
function CheckPassword(paswd) {
var submitFlag = false;
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*_])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if (document.reg_indi_form.pswd.length > 0) {
if (!document.reg_indi_form.pswd.value.match(paswd)) {
submitFlag = true;
document.getElementById('i3').innerHTML = "Use atleast one digit,character,specialCharacter";
document.getElementById('i3').style.color = "red";
document.getElementById('i10').style.fontSize = "12px";
//return false;
}
}
return submitFlag;
}
function alls() {
var valid = true;
valid *= req();
valid *= validateUname();
valid *= CheckPassword(this);
valid *= num();
valid *= confirm_pswd();
valid *= namevalid();
valid *= ValidateEmail(this);
return valid ? true : false;
}
I am calling alls() on onSubmit.
All other functions which are not working are similar to checkPassword().
HTML code:
<form name="reg_indi_form" method="post" onSubmit="return alls()" enctype="multipart/form-data" >
<table height="100" width="1000">
<tr>
<td>
First Name<font color="#FF0000">*</font>:
</td>
<td>
<input name="txt_fnm" type="text" id="txt_fnm"/> <label id="i"></label>
</td>
</tr>
<tr>
<td>
Password<font color="#FF0000">*</font>:
</td>
<td>
<input type="password" name="pswd" id="pswd"/><label id="i3"></label>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
<td>
<input type="reset" name="reset" value="Reset"/>
</td>
</tr>
</table>
</form>
Considering that your CheckPassword() returns true when the password is correct.
Now in your CheckPassword() function, document.reg_indi_form.pswd.value.match(paswd) this statement returns true if the pattern matches. You have added ! means it will return true when password doesn't matches to the given pattern. I have edited the function below, also consider using boolean operators instead of using multiple/nested if statements where ever possible. You don't have any field with id i10 I think it should be i3 instead.
function CheckPassword() {
var submitFlag = false;
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*_])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if ((document.reg_indi_form.pswd.length > 0) && (document.reg_indi_form.pswd.value.match(paswd))) {
submitFlag = true;
}
else{
document.getElementById('i3').innerHTML = "Use atleast one digit,character,specialCharacter";
document.getElementById('i3').style.color = "red";
document.getElementById('i3').style.fontSize = "12px";
}
return submitFlag;
}
And finally why are you using *= operator for boolean values in your alls() function? You should use boolean operator. Also this passes the current form or field object to the function, it is not required in this context since you are using document.formName.fieldName to access the fields of the form. Also the ternary (bool?value1:value2) operator at the end is unnecessary.
function alls() {
var valid = req()
&& validateUname()
&& CheckPassword()
&& num()
&& confirm_pswd()
&& namevalid()
&& ValidateEmail();
return valid;
}
When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.
I'm trying to validate a password using javascript, It's to make sure that when changing the password, the new password entered is equal to that of the re-entering of the new password (user is asked to enter their new password twice so both have to match) but at the same time, i want to make sure that the new password is at least 6 characters long, I have these functions separately but don't know how to combine them... thanks for help in advance!
This is what i have so far...
This is to make sure the new passwords match:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
<!-- if they match, go to next page -->
if ( new_password == confirm_new_password)
{
return true;
}
<!-- if they don't match, an error message is displayed -->
else
{
alert("Passwords do not match.");
}
return false;
}
This is for length of password:
function validatePassword()
{
if (document.getElementById("new_password").value.length < "5")
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
return true;
}
How do i combine both of these to form a SINGLE function where the two new passwords are checked so that they match, and also check that they are longer than 6 characters?
To just combine your two functions, this would work:
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (new_password.length < 5)
{
<!--If pasword is less than 5 characters long, display error message-->
alert("Please ensure your password is at least 6 characters long.");
return false;
}
else if ( new_password != confirm_new_password)
{
alert("Passwords do not match.");
return false;
}
else
{
return true;
}
}
Although I agree, there are better procedures out there. And please, make sure you're doing server-side validation as well since client-side validation is very easy to skip around.
i m not sure but you can call validatePassword() this function inside
if ( new_password == confirm_new_password)
{
validatePassword();
}
You have two options, either make the two functions a single function, or make them two separate functions and call them both before you submit / process your form.
if (validatePasswordLength() && validatePasswordsMatch()) {
// Continue
}
you have to try this code that is small and working.
if(document.getElementById("new_password").value != document.getElementById("confirm_new_password").value){
alert("Passwords do not match.");
return false;
}
<script>
function validatePassword()
{
var new_password = document.getElementById("new_password").value;
var confirm_new_password = document.getElementById("confirm_new_password").value;
if (document.getElementById("new_password").value.length < "5")
{
alert("Please ensure your password is at least 6 characters long.");
return false;
}
if (new_password == confirm_new_password)
{
alert("Password no match");
return false;
}
return true;
}
</script>
<form action="" onsubmit="return validatePassword()">
<p>New Password: <input type="password" id="new_password" name="new_password" /></p>
<p>Confirm Password: <input type="password" id="confirm_new_password" name="confirm_new_password" /></p>
<p><input type="submit" value="submit" /></p>
</form>