Trying to validate form field with jQuery - javascript

I know I must be missing something super simple here, because in theory this code is supposed to work, but it's not, and I cannot understand why. I'm trying to work out my own jQuery form validation, because I tried the jQuery form validator plug-in, and while setting up the rules and messages is perfectly simple, figuring out how to get the error message to show up where I wanted it to was a nightmare (couldn't get the message to show up AFTER radio buttons, for example.)
I've got the 1st part of my attempted validation working, but I can't clear the message once you enter something in the field. Also, the message pops up even when conditions are met, which doesn't make sense to me.
here's the jsfiddle
html
<form>
<p>
<lable for="name">Enter your name:</lable>
<input type="text" id="name" name="name">
<span class="error"></span>
</p>
<lable for="age">Enter your Age:</lable>
<input type="text" id="age" name="age" width="3">
<span class="error"></span>
</p>
</form>
jQuery
$("input").focusin(function(){//highlight input field on focus
$(this).css("background-color", "yellow");
});
$("input").focusout(function(){
$(this).css("background-color", "white");
});
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this))){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
$("#name").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this)) != false){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
$("#age").focusout(function(){//check that the field isn't empty
if ($(this).val() == ""){
$(this).next(".error").text("You forgot to enter your name!");
} else {
$(this).next(".error").text("");
}
});

You forgot the $(this).val()
$("#name").keyup(function(){ //check against non-letter characters in name field
var notLetter = /[^A-Za-z]/;
if (notLetter.test($(this).val())){
$(this).next(".error").text("Letters only please!");
} else {
$(this).next(".error").text("");
}
});
and again at age
$("#age").keyup(function(){//check against non-number characters in age
var notNumber = /[^0-9]/;
if (notNumber.test($(this).val())){
$(this).next(".error").text("Numbers only please!");
} else {
$(this).next(".error").text("");
}
});
also you can remove != false - e.g
if (test != false)
is the same as
if (test)
Heres the fixed up fiddle

Need to Remember Some thing while validating form Using JS:-
Check input value Using (this).val();
if Error Occur then forward to next vale with Error .
Check test value is false or true using if (test != false) or if (test)
then forward your Control for success page

You can use the lettersonly rule.
Here's an example:
Define a variable validator and do this :
validator = $("form").validate({
rules: {
name: { required: true,
lettersonly: true
}
}
});
It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate() call:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
you need to call
$("form").valid()
and if it is valid means without any errors then do :
validator.hideErrors();
$("form" div.has-error").removeClass("has-error");
For age input for numeric only jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

Related

Require at least one value for a group of inputs and a textarea

I have five fields, four text and one textarea that need to be required. However, they all don't need a value. At least one does though. They have been grouped with the class 'onair' and what I want is to integrate them into my current validate() script in the header if possible or at least show an alert message indicating that at least one field must be entered.
Here's what I got for a form validator in the /head.
<script language="javascript">
<!--
function validate(join)
{
//
// Check for a first name.
//
if (join.fname.value.length == 0)
{
alert("Please enter your first name.");
join.fname.focus();
return false;
}
//
// Check for a last name.
//
if (join.lname.value.length == 0)
{
alert("Please enter your last name.");
join.lname.focus();
return false;
}
//
// Check for an e-mail address.
//
if (join.email.value.length < 5)
{
alert("An email address is required to proceed.");
join.email.focus();
return false;
}
//
// Check for a valid e-mail address.
//
if (join.email.value.indexOf("#",".") == -1)
{
alert("A valid e-mail address is required to proceed.");
join.email.focus();
return false;
}
// It continues.
</script>
As you can see, for the most part, this does fine. However, these only work for a single field. This is the group I'm having trouble with.
<input type="text" class="onair" id="facebook" name="facebook" />
<input type="text" class="onair" id="skype" name="skype"" />
<input type="text" class="onair" id="twitter" name="twitter" />
<input type="text" class="onair" id="web" name="website" />
<textarea class="onair" id="other" name="other"></textarea>
What I'm wondering is, is there a way to validate by class name instead of by Id? Something that might add the values of each field to check for a count of null or zero?
I've done my searching around, but nothing I've seen actually shows an alert message window that I can customize myself. Also, I'm fairly new to jQuery and JavaScript, so if you could add the opening details and tell me where it goes if it cannot be integrated into my script already, that would be appreciated. Thanks!
You can view the page here...
https://www.itsjustgenoj.com/wp-content/test.html
Note: I'm sorry about the CSS. I stripped it all out on the example above.
Here's Something to validate them fields.
var all = document.querySelectorAll(".onair");
var supplied = 0;
for(var i = 0;i < all.length;i++){
var input = all[i];
if(input.value.length > 0)
{
//get the value by "input.value"
supplied++;
}
}
if(supplied < 1){ alert("Your Message Here"); }
else{
//do whatever after
}
function validate(join)
{
//
// Check for a first name.
//
if (join.fname.value.length > 0)
{
// do more validation if you want
return true;
}
//
// Check for a last name.
//
else if (join.lname.value.length > 0)
{
return true;
}
//
// Check for an e-mail address.
//
else if (join.email.value.length >0)
{
if (join.email.value.length < 5)
{
alert("An email address is required to proceed.");
join.email.focus();
return false;
}
else if (join.email.value.indexOf("#",".") == -1)
{
alert("A valid e-mail address is required to proceed.");
join.email.focus();
return false;
}
else
{
return true;
}
}
// It continues.
else if(join.fname.value.length == 0)
{
alert("Please enter your first name.");
join.fname.focus();
return false
}
else if(join.lname.value.length == 0)
{
alert("Please enter your last name.");
join.lname.focus();
return false
}
// It continues.
} End function
I presume you want to us your validate method with your join form passed as an argument.
If yes you can use querySelectorAll to get your inputs
function validate(join) {
onairInputs = join.querySelectorAll('.onair')
onairInputs.forEach((x) => console.log(x.value))
}
I see that you have some default values in your fields so you will want some custom logic there, as checking that value is simply empty will not work.

Javascript disable space key for change password textboxes

,Hi all,
var veri = {
YeniSifreTextBox: $('#YeniSifreTextBox_I').val(),
YeniSifreTekrarTextBox: $('#YeniSifreTekrarTextBox_I').val(),
};
if (veri.YeniSifreTextBox == '' || veri.YeniSifreTekrarTextBox == '') {
alert("Password Can not be empty!");
}
else if (veri.YeniSifreTextBox != veri.YeniSifreTekrarTextBox) {
alert("Passwords dont not match !");
}
I can control password can not be empty and passwords dont not match with above codes.
I want to disable to enter space key while user write password.
User must never use space in keyboard inside of 2 textboxes.
1.textbox YeniSifreTextBox_I
2.textbox YeniSifreTekrarTextBox_I
You can use the below javaScript code to block the space key,
function RestrictSpace() {
if (event.keyCode == 32) {
return false;
}
}
HTML
<textarea onkeypress="return RestrictSpace()"></textarea>
Hope this helps you.
<input type="number"
id="cardNumber"
name="cardNumber"
required
onKeyDown="if(event.keyCode === 32)
return false;">
You can implement the same functionality, without creating a custom function.

Show hide div and script based on radio button

I'm trying to implement validation into my form being conditional. Basically if the user selects email radio option then email is going to be required, or if phone is selected then phone field would be required.
So far I've gotten this code to work, form submits and validation works fine. But if I switch to phone, then switch back to email, the validation is loaded so form won't submit if I haven't filled out both fields.
I have it set that way but basically trying to make it so if one field is selected then the other required. Any better ways to do this?
HTML:
<label>Method of Contact</label>
<label class="radio">
<input type="radio" name="group" value="ck1" checked/>
Email
</label><br />
<label class="radio"><input type="radio" name="group" value="ck2" />
Phone
</label>
<div id="emaildisp">
<label>Email</label>
<input id="emailv" name="email" type="email" />
</div>
<div id="phonedisp">
<label>Phone</label>
<input id="phonev" name="phone" type="text" />
</div>
Javascript:
$(function()
{
if (jQuery('input[value=ck2]:checked').length > 0)
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
jQuery('input[name=group]').change(function()
{
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2')
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
});
Solution:
Thanks to the answers below, I came up with the solution. Key difference, I was not using jquery validation plugin, rather a different validation script. So I switched over, for beginners, just look it up you'll simply have to add link to the script in the header.
Next I gave the form an id, #myform. Then I have the ck1 and ck2 radio button their own respective ids, #ck1id and #ck2id. And using the below code, if the radio button is selected, then depending on the id selected, next part becomes validation required.
<script type='text/javascript'>
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
}
});
jQuery('input[name=group]').triggerHandler('change');
});
</script>
<script>
$(function(){
// validate signup form on keyup and submit
$("#myform").validate({
rules: {
group: "required",
email:
{
required: '#ck1id:checked',
email: true
},
phone:
{
required: '#ck2id:checked',
digits: true
}
},
messages: {
group: "Please select one",
email: "Please enter your email.",
phone: "Please enter your phone."
}
});
});
</script>
You need to remove the previously added validation from the other fields those are not required. If you need phone remove validation from email and vice versa.
You can follow two way, either remove validation or ignore the validation.
1. Removing the validation:
jQuery("#emailv").rules('remove');
or
jQuery("#phonev").rules('remove');
2. Ignore validation:
jQuery("#emailv").validate({
ignore: "#emailv"
});
or
jQuery("#phonev").validate({
ignore: "#phonev"
});
Check if this helps you.
Use .rules("remove") to remove jquery validation.
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#emailv").rules("remove"); //remove the other field validation
jQuery("#phonev").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#phonev").rules("remove"); //remove the other field validation
jQuery("#emailv").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
jQuery('input[name=group]').triggerHandler("change");
});
I see that you have duplicated code, just remove it and use jQuery('input[name=group]').triggerHandler("change"); to trigger it when page first loads

Using jQuery to prevent form submission when input fields are empty

The solution should be pretty straightforward. I'm trying to prevent the form from submitting properly when no value is found within the input boxes. Here's my JSFiddle: http://jsfiddle.net/nArYa/7/
//Markup
<form action="" method="post" name="form" id="form">
<input type="text" placeholder="Your email*" name="email" id="email">
<input type="text" placeholder="Your name*" autocomplete=off name="name" id="user_name"
<button type="submit" id="signup" value="Sign me up!">Sign Up</button>
</form>
//jQuery
if ($.trim($("#email, #user_name").val()) === "") {
$('#form').submit(function(e) {
e.preventDefault();
alert('you did not fill out one of the fields');
})
}
As you can see in the JSFiddle, the problem is that when I type something into both fields, the alert box STILL pops up. I'm having a hard time figuring out why. Is there something wrong within my
if($.trim($"#email, #user_name").val()) === "") ?
Two things, #1 the check for empty fields should happen on every attempt of submit, #2 you need to check each field individually
$('#form').submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
alert('you did not fill out one of the fields');
return false;
}
});
Updated fiddle
Your check occurs on page load. You need to check the field when the form is submitted.
$('#form').submit(function(e) {
if ($.trim($("#email, #user_name").val()) === "") {
e.preventDefault();
alert('you did not fill out one of the fields');
}
});
HTML5: use required in input tag
A boolean attribute.
Input field must be filled out before submitting the form.
Works with text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
<input required type='text'...>
w3schools hint
I guess that this will help:
$('#form').submit(function(e) {
e.preventDefault();
$("#email, #user_name").each(function(){
if($.trim(this.value) == ""){
alert('you did not fill out one of the fields');
} else {
// Submit
}
})
})
Put your if statement inside the callback:
$('#form').submit(function(e) {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val())) {
e.preventDefault();
alert('you did not fill out one of the fields');
//You can return false here as well
}
});

JS validation issue

My validation function looks like that.
var fname = $("#fname").val();
var lname = $("#lname").val();
function validate() {
var isValid = true;
if (!fname) {
$("#fname").attr('class', 'invalid');
isValid=false;
}
if (!lname) {
$("#lname").attr('class', 'invalid');
isValid=false;
}
It simply changes the class of unfilled input box.
I know that i can write else for every if and change back to default (class="valid") if user fills some of inputs. But how can i create something universal for all inputs to change back to default class the input that user has filled after first validation error?
That was good Tural! HOWEVER, why the excess processing in your code? That will add unecessary stress. Since you, for what you "solved", will add the "valid" class to ALL the input type text or password, just add that to the actual input element in the straight code:
<input class='valid' ..... />
Now, back to your original validation: why not make it universal?:
function validate(formField) {
if !formField $('#'+formField).removeClass('valid').addClass('invalid');
}
Or something in that vein ...
You can either assume everything is valid and then try to disprove that or you can try to prove its validity. The below takes the first approach and sets all the classes to "valid" to be consistent with that.
function validate() {
// Get the current form input state.
var fname = $("#fname");
var lname = $("#lname");
// Assume everything valid until proven otherwise.
var isValid = true;
fname.attr('class', 'valid');
lname.attr('class', 'valid');
if (!fname.val()) {
fname.attr('class', 'invalid');
isValid=false;
}
if (!lname.val()) {
lname.attr('class', 'invalid');
isValid=false;
}
return isValid;
}
Ok. I found the way
$('input[type="text"],input[type="password"]').keypress(function () {
$(this).attr('class', 'valid');
});

Categories

Resources