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.
Related
This is my first time posting here since I haven't been able to find a specific answer for my question anywhere so apologies if I'm doing something wrong.
Anyway, I wanted to know if there was a way to convert text from a form input to a string and grab a substring of that text?
For example if I have a form input like this:
<form onsubmit="return formValidation()">
<input type="text" name="foo">
</form>
Can I grab whatever is typed into that input like so?
function myFunction() {
var string = document.getElementByName('foo').value;
// Code converting the selected element to a string
var index = string.substring(0, 2);
// Rest of code
}
I have little experience in JavaScript so I'm confused on how to convert an element to string. jQuery solutions are welcome.
I wanted to do this for an ID number validation on a form, which basically checks the first two indexes of an 8-digit ID number to see if it's a known ID number in my school district.
Thanks!
EDIT:
Okay so since people actually saw this, could anyone tell me what's wrong with this code? It's returning false even for numbers starting with the numbers here.
function formValidation() {
var idInput = document.getElementsByName('idNumber')[0].value;
var idNumber = idInput.substring(0, 2);
if(idNumber === "71" || idNumber === "81" || idNumber === "53") {
alert("Your form has been submitted. You will now be redirected to a confirmation page.");
return true;
} else {
alert("Please input a valid ID number. If the first two integers of your ID do not match the school district standard, contact a club leader.");
return false;
}
}
Is the method I'm using to compare strings wrong?
Problem is: document.getElementByName('foo').value, you have missed s
document.getElementsByName('foo')
^
document.getElementsByName('foo') gives you NodeList, not just a single HtmlElement,
Use instead:
document.getElementsByName('foo')[0].value;
Edited: Have a look at below functional code.
function formValidation() {
var idInput = document.getElementsByName('idNumber')[0].value;
var idNumber = idInput.substring(0, 2);
if (idNumber === "71" || idNumber === "81" || idNumber === "53") {
alert("Your form has been submitted. You will now be redirected to a confirmation page.");
return true;
} else {
alert("Please input a valid ID number. If the first two integers of your ID do not match the school district standard, contact a club leader.");
return false;
}
}
<form onsubmit="return formValidation();">
<input type="text" name="idNumber" autofocus="" value="71456" maxlength="8" />
</form>
I have an input field for which I need to make sure the input is only and only characters from the alphabet, with no:
numbers
special characters
number + alphabet combinations
I want to do this using if else statement only. So far the code is:
HTML:
<form id="myform" onsubmit="return check();" >
<input class="input" type="text" name="firstname">
And JavaScript is:
function check() {
var x = document.forms["myform"]["firstname"].value;
if (x == null || x == ""){
myform.action="firstnameerror.html";}
if (isNaN(x)) {
myform.action="lastname.html";
} else {
myform.action="firstnameerror1.html"
}
}
You can check it using regular expressions (RegExp), specifically with the .test() function:
if(/[^a-zA-Z]/.test(x))
// code to throw error
This will run the code to throw an error if any non-alphabetic character is contained in x.
I have a problem with my code I have a validation. I have an existing validation that can validate letters and special characters in the textfield that prevent the user from typing letters and special characters.
And I want to include that validation with my code but I dont know how.
Here's a bit of my code:
<input type="text" class="col-md-5 quantity text-center" id="base_<?php echo $product['product_id']; ?>" name="quantity" value="<?php echo $product['quantity']; ?>" required="required" onKeyup="setQty(<?php echo $product['product_id']; ?>);" /> pcs.
...
This is the javascript validation
function setQty(id) {
//validate if have a value and the value is not equal to 0
if($("#base_"+id).val().length > 0 && $("#base_"+id).val() != 0){
alert("YES");
} else {
alert("NO");
}
}
And this is the existing function that can validate the letters and special char.
$(".quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
return false;
}
});
I want to include that in my if statement. But I dont have an idea.
Can you give me a more simple solution for this?
Ok that's all thanks.
JQuery has a lot of plugins for this, like the masked input plugin.
You'll have to 'import' the code of it, and use it, like
$("#quantity").mask("99");
And you can customize the placeholder, for example (it's all in the documentation):
$("#quantity").mask("99", {placeholder:" "});
Since it's a product quantity, I assumed it wont pass two digits. That's the advantage of using this plugin.
Other solution is using html 5, with the number input. It's pretty simple, actually. You said you want something more simple, so I recommend this one:
<input type='number' .../>
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.
I am new with JavaScript validation and learning I am trying to validate form but I am getting issue with condition.
In my form I have one field which is name and one submit button.
What I am trying is:
If user click to to submit button and text box is empty give alert('Please enter your First Name.')
Then If user entered value which is not allowed by regex give alert('Please enter only letters no special character allowed.');
but I am getting first alert every time. Whats wrong i don't understand.
My Code:
jQuery('#send').click(function () {
var reg_first_name = /^[A-Za-z ]{3,20}$/;
var first_name = jQuery('#sa_first_name').val();
if(first_name.length > 0){
alert('Please enter your First Name.');
document.getElementById("sa_first_name").focus();
return false;
}
if (!reg_first_name.test(first_name)) {
alert('Please enter only letters no special character allowed.');
document.getElementById("sa_first_name").focus();
return false;
}
return false;
});
Can you guide me?
In case the user enters a name the first_name.length > 0 will always be true.
You can check it like
if($.trim(first_name) == '')
to also avoid only spaces
condition is wrong
if(first_name.length > 0){
if you want to check that first_name must have value then your condition must be
if(first_name.trim().length == 0){