Javascript not validating password in Form - javascript

Hi I have looked around online and I am aware that similar questions have been asked, however, I am unable to find a suitable solution to my problem. I need this code to be password validated, the problem is that I'm not directly working with an <input> field therefore I've been unable to figure out how to implement JS.
Here is the HTML (it's implemented using ruby-on-rails, this is all the 'HTML' side that I can see (full code in fiddle below))
<form accept-charset='utf-8' method='post' name="form" action='register' class="registerform" onsubmit="return validate_form()">
<h3 class="registernospace">Contact Information</h3>
<table>
<tbody>
<tr><td class="registerrowspace" colspan="2">The Password must be at least 6 characters long and should contain a mixture of lower case letters, upper case letters, and numbers.<br />The Confirm Password must match the Password.</td></tr>
<tr><th class="registerrowspace">Password</th><td id="password1" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Confirm Password</th><td id="password2" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Date of Birth</th><td class="registerrowspace">
</tbody>
</table>
<% end %>
<input type='hidden' name='register_submitted' value='yes'/>
<p><input type='submit' class="button" value='Register Now' /></p>
</form>
And I have tried Implementing some JS (but being unfamiliar with the language I haven't been able to get it working, but I was trying to do something like this:
<script type="text/javascript">
function validate_form()
{
var passw = document.getElementById('password1').value;
if(passw.value.length < 6 ) {
alert("Error: Password must contain at least six characters!");
form.password.focus();
return false;
}
return true;
}
</script>
So I was hoping it validates and raises a message if its blank, if its < 6 chars and if it does not include a Uppercase and a number. Although I'm aware I haven't introduced the latter in the code, I couldn't even get the <6 to work.
Also I have other validations (which were built by default which work) and you can see the full:
Fiddle code
Live Website

if(passw.value.length < 6 ) {
should be
if(passw.length < 6 ) {
because you already get its value
var passw = document.getElementById('password1').value;
UPDATE:
password1 is <td> id not of password feild
i just check your link, it was giving error passw is undefined in console, you password field id is password-input-0, so use
var passw = document.getElementById('password-input-0').value;

^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$
---
^.* : Start
(?=.{6,}) : Length
(?=.*[a-zA-Z]) : Letters
(?=.*\d) : Digits
(?=.*[!#$%&? "]) : Special characters
.*$ : End
function validatePassword() {
var newPassword = document.getElementById('changePasswordForm').newPassword.value;
var regularExpression = ^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$/;
alert(newPassword);
if(!regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}
}

Instead of using if(passw.value.length < 6 ) use if(passw.length < 6 ) you have already value of password you only need to check for size.
Also, Your textfield name is wrong. 'Password1' is td name not password textfield. Please check and correct.

if(passw.length < 5 ) //here should be 5
Page refreshes when you click the button :you don't call e.preventDefault(); I think you should listen 'submit' event. In the 'listen' function you may validate the length of the input and prevent it's default behavior.

Related

The form does not work correctly when sent

I wrote the code for a form validation.
Should work like this:
It checks (allLetter (uName)) and if it's true, then validate the next input.
If any validation is false then it should return false.
My problem is that if both validations are true, then everything is exactly false and the form is not sent.
If I set true in formValidation (), if at least one check false, the form should not be sent.
<form name='registration' method="POST" onSubmit="return formValidation();">
<label for="userName">Name:</label>
<input type="text" name="userName" size="20" />
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" size="20" />
<input type="submit" name="submit" value="Submit" />
</form>
function formValidation() {
var uName = document.registration.userName;
var uPhone = document.registration.userPhone;
if(allLetter(uName)) {
if(phone(uPhone)) {}
}
return false;
}
function phone(uPhone){
var digts = /^[0-9]+$/;
if(uPhone.value.match(digts)){
return true;
} else {
alert('Phone must have only digits');
uPhone.focus();
return false;
}
}
function allLetter(uName) {
var letters = /^[A-Za-z]+$/;
if(uName.value.match(letters)) {
return true;
}else{
alert('Username must have alphabet characters only');
uName.focus();
return false;
}
}
First, you are using a 20+ year old way to gain references to your elements (document.form.formElementNameAttributeValue) and, while this still works for legacy reasons, it doesn't follow the standard Document Object Model (DOM) API.
Next, you've broken up your validation tests into different methods (and that's certainly not a bad idea for reusability), but in this case is is adding a ton of code that you just don't need. I've always found it's best to start simple and get the code working, then refactor it.
You're also not using the <label> elements correctly.
One other point, your form is set to send its data via a POST request. POST should only be used when you are changing the state of the server (i.e. you are adding, editing or deleting some data on the server). If that's what your form does, you'r fine. But, if not, you should be using a GET request.
Lastly, you are also using a 20+ year old technique for setting up event handlers using inline HTML event attributes (onsubmit), which should no longer be used for many reasons. Additionally, when using this technique, you have to use return false from your validation function and then return in front of the validation function name in the attribute to cancel the event instead of just using event.preventDefault().
So, here is a modern, standards-based approach to your validation:
// Get references to the elements you'll be working with using the DOM API
var frm = document.querySelector("form[name='registration']");
var user = document.getElementById("userName");
var phone = document.getElementById("userPhone");
// Set up event handlers in JavaScript, not with HTML attributes
frm.addEventListener("submit", formValidation);
// Validation function will automatically be passed a reference
// the to event it's associated with (the submit event in this case).
// As you can see, the function is prepared to recieve that argument
// with the "event" parameter.
function formValidation(event) {
var letters = /^[A-Za-z]+$/;
var digts = /^[0-9]+$/;
// This will not only be used to show any errors, but we'll also use
// it to know if there were any errors.
var errorMessage = "";
// Validate the user name
if(user.value.match(letters)) {
// We've already validated the user name, so all we need to
// know now is if the phone is NOT valid. By prepending a !
// to the test, we reverse the logic and are now testing to
// see if the phone does NOT match the regular expression
if(!phone.value.match(digts)) {
// Invalid phone number
errorMessage = "Phone must have only digits";
phone.focus();
}
} else {
// Invalid user name
errorMessage = "Username must have alphabet characters only";
user.focus();
}
// If there is an error message, we've got a validation issue
if(errorMessage !== ""){
alert(errorMessage);
event.preventDefault(); // Stop the form submission
}
}
<!-- 20 is the default size for input elements, but if you do
want to change it do it via CSS, not HTML attributes -->
<form name='registration' method="POST">
<!-- The for attribute of a label must be equal to the id
attribute of some other element, not the name attribute -->
<label for="userName">Name:</label>
<input type="text" name="userName" id="userName">
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" id="userPhone">
<input type="submit" name="submit" value="Submit">
</form>

JavaScript validating input only contains integers on submit

I've been trying for a bit to find a good way to go about this. Here's the trick this is being developed for IE6, so HTML5 is not supported (which is what is making this a pain, and why the button is actually a span). I need to allow all input into the input element but on submit i need to verify that the input is an integer and if it contains alpha characters or decimals throw an error.
<table id="studentIdInputTable">
<tr><td colspan="3"><hr class="style-hr" /></td></tr>
<tr><td><span class="underline bold">Selection 1</span></td>
<td class="center"><span class="small-text">Employee ID</span></td>
</tr>
<tr><td>Please enter your Student ID to <span class="bold italic">start your registration process</span></td>
<td class="center"><input type="text" maxlength="11" id="tbNewStudentId" /></td>
<td> <span id="btnNewStudent" class="validation-button">Start</span></td></tr>
</table>
I have javascript native to the HTML page as below
function CheckNewStudentId(){
var newStudentID = $("tbNewStudentId").val();
newEmployeeID = parseInt(newEmployeeID, 10);
var isNum = /^\d+$/.test(IDnumber);
if (isNum == false) {
alert(IDnumber + " is not a valid student number. Please enter only numbers 0-9, containing no alphabetical characters.");
}
}
It would be easier if this was for a more updated browser platform. Any ideas how I can go about this?
Edit***
For reference to other users this was solved using this function
function validIdCheck(Input){
if(Number.isInteger(Input)==false){
alert("This is not a valid ID");
}
}
connected to this jQuery click function
$("#btnNewStudent").click(function(){
var newStuId = $("#tbNewStudentId").val();
newStuId=parseInt(newStuId);
validIdCheck(newStuId);
});
To check if a number is an integer try this. It returns a boolean.
Number.isInteger(yourNumber)
docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
Using part of your code:
function validateStudentId(id) { return /^\d+$/.test(id) }
This will return true if it is a number or combination of numbers from 0 to 9.
If the id can not start with a 0, try this:
function validateStudentId(id) { return /^([1-9]|[1-9]\d+)$/ }
Quick explanation:
^ starts with
[1-9] digit between 1 and 9
| or
\d digit (0 to 9)
+ occurs at least once and up to unlimited times
$ ends with
Test it here

Form submit with 2 different errors depending on input value - 1 is not working

I posted a question on how to make 2 errors work here: Multipile forms with input and submit button with the same action with Javascript
I needed 2 errors, 1 error if the input if less than 15 digits, the second error is if the input begins with 9900 (if it does, there is an error and then it redirects to a different page).
It worked for a while, although suddenly it stopped giving the second error (if input starts with 9900), the page is: http://www.unlocker.co.il/shop/sim-unlock-htc-mobile-device/
Each form has it's own id: unlock1, unlock2, unlock3 etc.
the JS files include:
jQuery(function($){
$('form#unlock1').on('submit', function (e){
if($('form#unlock1 > input.the_imei').val().length == 15){
if($(this).val().indexOf('9900') === 0){
alert('לפי המספר IMEI, ברשותכם מכשיר CDMA, אנא ראו מידע נוסף בעמוד פתיחת מכשירי CDMA');
window.location = 'http://www.unlocker.co.il/sim-unlock-cdma-mobile-device';
e.preventDefault();
}
return;
}
alert('אנא מלאו מספר IMEI בעל 15 ספרות');
e.preventDefault();
});
})
and the Forms are:
<form id="unlock1" class="cart" enctype="multipart/form-data" method="post" name="unlock"> <input class="the_imei" style="width: 80%; border-radius: 15px;" name="the_imei" type="text" value="" placeholder="מספר סידורי IMEI של המכשיר (חייג #06#*)" /> <input class="add-to-cart" name="add-to-cart" type="hidden" value="39" /> <button class="unlockButton" type="submit" value="submit">פתח לכל הרשתות בישראל </button> </form>
Each form has a different id (example Unlock1) and on it's own JS file the id like listed in 2 places.
I can't figure out why the "minimum 15 digits" error works, but the "if input begins with 9900" error does not work anymore.
Thanks!
This is how I would do this. Try to avoid using too many nested if statments. Instead create the escape clauses with return statements when the user enters the incorrect value first.
$('form#unlock1').on('submit', function(){
var $el = $('form#unlock1 > input.the_imei');
if($el.val().length<15){
//Not enough characters
return false;
}
if($el.val().substring(0,4)=='9900') {
//Value begins with 9900
return false;
}
//User has entered a correct imei
});

HTML5/JS/jQuery: On invalid input, mark a different (arbitrary) element as invalid

I am trying to create one of those standard new password forms, where you type the new password once and then a second time to confirm. I would like it so that once you blur away from these fields, if they don't match, both will be marked invalid, as in the following scenario:
User enters password abc into #newpassword1.
User tabs to #newpassword2.
User enters password def into #newpassword2.
User tabs away.
Validation detects a mismatch, and marks both #newpassword1 and #newpassword2 as invalid.
I know that i can mark the target of an event as invalid by using e.target.setCustomValidity(...), but i don't understand JavaScript's event model very well and can't figure out how to mark a different element as invalid based on the event target's own invalidity.
This is the relevant excerpt of (non-working) code that i am trying to use:
if ( $('#newpassword1').val() != $('#newpassword2').val() ) {
errorMessage = "The new passwords you've entered don't match.";
$('#newpassword1, #newpassword2').setCustomValidity(errorMessage);
}
This seems like it should work, intuitively, but of course it does not. The error is simply TypeError: $(...).setCustomValidity is not a function.
Please note: I am not asking how to add a red ring or whatever to a field, i want it to actually be invalid (as in, have its validity.valid property return false).
Is it possible to do this?
Thanks!
Try the below code. You are getting that error because jQuery returns an array of selected objects and since setCustomValidity is supported by native input elements and not jquery objects, you are seeing that error.
$('#newpassword1, #newpassword2').each(function() {
this.setCustomValidity(errorMessage)
});
<div class="cabinet_settings_header cabinet_header">Список регионов работы для выбора</div>
<div class="registration_region_select checkbox-group required">
<?for($i = 0; $i < sizeof($regions); $i++):?>
<label for="region_id_<?=$regions[$i]['region_id']?>">
<input type="checkbox" name="region_id[]" value="<?=$regions[$i]['region_id']?>" id="region_id_<?=$regions[$i]['region_id']?>" />
<?=$regions[$i]['name']?>
</label>
<?endfor;?>
</div>
<div class="cabinet_settings_header cabinet_header">Проверка выбора регионов работы (разрешмет отправку формы, если минимум 1 выбран)</div>
$('.checkbox-group.required input').on('change', function(){
checkRegions();
});
function checkRegions(){
checked_counter = $('.checkbox-group.required :checkbox:checked').length;
if(checked_counter > 0){
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('');
}else{
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('Выберите хотябы 1 из вариантов');
}
}
$(document).ready(function() {
checkRegions();
$("form").submit(function(event){
if($('.checkbox-group.required :checkbox:checked').length <= 0 ){
$('.checkbox-group.required #region_id_2').focus();
event.preventDefault();
}
})
});

Javascript name validation

I have a javascript function written to validate a field on my form. This function is supposed to make sure the field is not empty, does not exceed the limit of 35 characters and only contains alphabetic characters and a hyphen(-). I had code to make sure the field is not empty and that it does not exceed 35 characters which worked fine but i added code to validate the field to the usable characters and i tested it out by leaving the field empty to make sure that still worked but when i hit the submit button the function didn't seem to validate at all, didn't give me an alert and just submitted. Here is my code:
function validateFamily()
{
var family=document.getElementById('family');
var stringf = document.getElementById('family').value;
if (family.value=="")
{
alert("Family name must be filled out");
return false;
}
else if (document.getElementById('family').value.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if (/[^a-zA-Z\-\]/.test( stringf ))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
return false;
}
return true;
}
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateFamily() && validateGiven() && validateMaleFemale() && validDate() && validateAddress() && validatePost() && validateParent() && validateWork() && validateHome() && validateMob() && validateCheckBoxes();">
<b>Student's Family Name</b>
<br>
<input type="text" id="family" name="family" /><?php echo $strmsgf; ?>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Could anyone show me how to fix my code?
Your regular expression is broken. You've escaped the closing square bracket around the character set. Try this:
else if (/[^a-zA-Z0-9\-]/.test( stringf ))
Also, there's a lot of weird clutter in there that's annoying but not fatal: How many times do you really need to call getElementById('family') in that method? Once.
if (stringf=="")
{
alert("Family name must be filled out");
return false;
}
else if (stringf.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if (/[^a-zA-Z0-9\-]/.test( stringf ))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
return false;
}
return true;
UPDATED:
Sorry, the problem is with your regex, i missed that, change to this its fully working:
var ck_password = /^[A-Za-z0-9-]/;
if(!ck_password.test(stringf))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
}
Console in chrome, go to the OPTIONS in the right top coner, select TOOLS, then DEVELOPER TOOLS.
Try to rename submit button, rid of id and name "submit" (rename to "doSubmit" or smth), it can cause problems and conflict with event "submit" of form.

Categories