I have this javascript which is working great -
var employeename = $("#employeename");
var employeenameInfo = $("#employeenameInfo");
employeename.blur(validateEmployeename);
function validateEmployeename(){
//if it's NOT valid
if(employeename.val().length < 4){
employeename.addClass("error");
employeenameInfo.text("We want names with more than 3 letters!");
employeenameInfo.addClass("error");
return false;
}
//if it's valid
else{
employeename.removeClass("error");
employeenameInfo.text("Full Name.");
employeenameInfo.removeClass("error");
return true;
}
}
However instead of having a big list of this functions for all my different fields I want to pass a field in e.g.
function validateGeneric(field){
However whatever I try just gives me errors and I'm really stuck. Any help appreciated. This also brings up another problem with the info field, any way I can store the orginal text and just restore that instead of a new string?
You can get the field that triggered the event using $(this). also you should put the info field as a sibling with an info class
$('input.to_be_validated').blur(validateInput);
function validateInput(e){
var input = $(this)
var info = input.parent.find('.info')
//if it's NOT valid
if(input.val().length < 4){
input.addClass("error");
info.text("We want names with more than 3 letters!");
info.addClass("error");
return false;
}
//if it's valid
else{
input.removeClass("error");
info.text("Full Name.");
info.removeClass("error");
return true;
}
}
Edit: forgot about the info field
All you need to do is to reference the field var you'd pass into your function, therefore your code becomes:
function validateEmployeename(field, fieldinfo){
//if it's NOT valid
if(field.val().length < 4){
field.addClass("error");
fieldinfo.text("We want names with more than 3 letters!");
fieldinfo.addClass("error");
return false;
}
//if it's valid
else{
field.removeClass("error");
fieldinfo.text("Full Name.");
fieldinfo.removeClass("error");
return true;
}
}
You may also use multiple selectors:
$("input[name='employeename'], input[name='employeename2']").blur(function() {
// put your validation routine for fields that should contain names
$(this).next("#employeenameInfo").html("info here"); // note that you don't have unique id here, better to find element you want to put your error message by tagname/class, like "span.error"
});
$("input[name='employeemail'], input[name='employeemail2']").blur(function() {
// put your validation routine for fields that should contain email addresses
$(this).next("#emailInfo").html("info here"); // note that you don't have unique id here, better to find element you want to put your error message by tagname/class, like "span.error"
});
That way you don't need to pass anything to validation functions, everything will be resolved around $(this), providing you've got proper elements to fill your error messages nearby:
<input type="text" name="employeename" />
<span class="error" />
Related
I'm making a form to change the password.
I ask for the current password and then there are two fields to put the new password.
I have two problems:
First: I need to check if the two fields of the new password are equal.I used onsubmit to check that.If they are the same, submit.If not it should show a message saying something.The problem is that it doesn't display.This is the code:
function checkform(){
var pass=myForm.pass.value;
var new=myForm.new.value;
var new=myForm.new2.value;
if(new!=new2){
document.getElementById("message").style.display='block';
document.getElementById("pass").value=" ";
document.getElementById("new").value=" ";
document.getElementById("new2").value=" ";
return false;
}else{
return true;
}
}
When I insert diferent new passwords it still submits, but if I delete that document.getElementById it doesn't submit.
Second problem: I have a php page (not using frameworks, just php) that is a class.When I want to acess a function of that class all I need to do is
include("class.php");
$my = new the_class(); $response= $my->check();`
The check() function retrives the password, so then I can check if the value from the field pass is the same as the $response.But how can I put this on the function checkform()? It doesn't work this way.
Don't take the variable name as new its a keyword it is reserved for creating an instance, so better take some other name to the variable and you may get what you're looking for.
**You Try below code**
function checkform(){
var pass=myForm.pass.value;
var new=document.getElementById("new").value();
var new=document.getElementById("new2").value();
if(new!=new2){
document.getElementById("message").style.display='block';
document.getElementById("pass").value=" ";
document.getElementById("new").value=" ";
document.getElementById("new2").value=" ";
return false;
}else{
return true;
}
}
I am using Javascript/Jquery and I have a dropdownlist. My first index is: "Please select an id". I want to submit the page (return true will submit it) if something is selected, else do not submit it.
<script type="text/javascript">
function Type() {
var id = $("[id$='ddl1']").val();
alert(id); // If something is selected i get the value else I get "Please select an id"
var valid = false;
if (id < 0) {
$("#Type-span").text("*"); //A Span to represent the * if page not submitted
}
else {
valid = true;
$("#Type-span").text("");
}
alert(valid);
}
</script>
It always returns true here, even if i select "Please select an id"
Please, try the below
var id = parseInt($("[id$='ddl1']").val(), 10);
To handle the NaN situation, you need to evaluate that too
if(id != id || id < 0)
and you should have value of element 'Please select an answer' as a blank.
Your issue is that the value attribute of is a string, so, if you are trying to compare it to 0, I'm assuming that it is a number and you will need to convert it to one, before doing the compare.
Change this:
var id = $("[id$='ddl1']").val();
. . . to this:
var id = parseInt($("[id$='ddl1']").val(), 10);
And, if the values of the <options> are not all numbers (with the default being < 0), then you need to make sure that they are. :)
I'm trying to leverage some form validation to do something it really wasn't designed to do. I have a table in my form and each row has a checkbox. I want to ensure that at least one of a specific type of checkbox is selected, if not I want to show a validation error. I am doing something similar with a text box with logic that looks like this:
function ValidateName() {
var $nameTextbox = $("#Name");
var $originalName = $("#OriginalName");
var nameText = $nameTextbox.val().toLowerCase();
var originalNameText = $originalName.val().toLowerCase();
//check to see if original name and group name match
if (nameText != originalNameText) {
//This isn't the same name we started with
if (uniqueNames.indexOf(nameText) > -1) {
//name isn't unique, throw validation error
var currentForm = $nameTextbox.closest("form");
//trigger validation
var errorArray = {};
errorArray["Name"] = 'Name must be unique';
currentForm.validate().showErrors(errorArray);
}
}
}
I've written something similar for the table and it works as long as I point the errorArray's index to the id of an input. However, I want to display the error somewhere more generic like the validation summary at the top of the form. How do I set up the error array to show on the form or the validation summary instead of a specific input? Is that even possible?
One way you could do this is you set a hidden input that is false when none are check and true if 1 or more are checked. You then listen to all the checkboxes by giving them all a class. I have an example shown below
http://jsfiddle.net/95acw2m9/
Html
<input type="hidden" id="IsCheckValue" name="IsCheckedValue" value="false"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
Jquery
$(document).ready(function(){
$(".someCheckbox").change(function(){
if($(".someCheckbox:checked ").length > 0){
$("#IsCheckValue").val("True")
}else{
$("#IsCheckValue").val("False")
}
})
})
Then pass that bool value in your model. In your controller method you can check the value of the bool. If the bool is false set the model to false like this
ModelState.AddModelError("Checkbox", "Must select one checkbox");
You can use the #Html.ValidationSummary() to display the error in your view.
I have a commenting system in PHP, in which there is loop to fetch articles. every article has a comment form which needs to be validated for null values.
Now problem is there is no limit to the number of these forms and ID of each form is coming from database. I want to validate each form but without writing the script multiple times.
How can i validate the form field for null value without writing script again & again.
Can i create a loop kind of thing in my script which check the field for null values.
My script is like this -
function validatecomments()
{
nums = ["1", "2", "3", "4"];
text = "commentform"; //form id is like this - commentform1, commentform2, ...
for (var i = 1; i < nums.length; i++) {
text = text + nums[i]; //to create it like form id
if (document.text.comment_emp_id.value=="")
{
alert("Please enter the Employee ID");
document.text.comment_emp_id.focus();
return false;
}
if (document.text.comment.value=="")
{
alert("Please give some Comments");
document.text.comment.focus();
return false;
}
}
}
this is snapshot of the comment form. here are 2 forms with POST button. Problem is i have a number of such forms in a page and i have to check them for null values. I am being forced to write script code multiple times.
Can anyone help me out.
you are not sending correct value to the script. try this
<form name="commentform<?php echo $your_id?>" action="" onSubmit="return validatecomments(this);" method="post">
in your script
function validatecomments(f)
{
if (f.elements['comment_emp_id'].value=="")
{
alert("Please enter the Employee ID");
f.elements['comment_emp_id'].focus();
return false;
}
else if (f.elements['comment'].value=="")
{
alert("Please give some Comments");
f.elements['comment'].focus();
return false;
}
}
May be it helps you.
<script>
function validate(){
u=document.CustomerLogin.UserName.value;
p=document.CustomerLogin.Password.value;
rp=document.CustomerLogin.RePassword.value;
if (u==""){
document.write("Enter a unique username");
return false;
}
if (p!=rp){
document.write("Retype Password Incorrect");
return false;
}
return true;
}
</script>
The messages are printed on separate page but i want them to be printed at the same place in front of text box! Please help. Thanks!
Never use Document write, it's hazardous...
document.getElementById("anidofanElementinthePage").innerHTML = " string to add by javascript";
<script>
function validate(){
u=document.CustomerLogin.UserName.value;
p=document.CustomerLogin.Password.value;
rp=document.CustomerLogin.RePassword.value;
if (u==""){
document.getElementById("theIdOfyourTextBlocInForm").innerHTML = "Enter a unique username";
return false;
}
if (p!=rp){
document.getElementById("theIdOfyourTextBlocInForm").innerHTML = "Retype Password Incorrect";
return false;
}
return true;
}
</script>
document.write will simply append the message to the end of the page. The simplest solution would be change it to an alert like this:
if (u==""){
alert("Enter a unique username");
return false;
}
Otherwise you will need to create new DOM elements(either before hand or when an error is detected) to hold the message and position them next to the inputs
you would need to detect text change. One way is to use this:
<input name="blah" onchange="validate()" ... />
EDIT
To add text on the same page, include the script using <script src=...> and then add <div id='validation[i]'></div> next to each of the inputs where [i] is increased by 1 each time (so validation1 validation2 so on). Then, use getElementById('validation[i]').innerHtml to change the value.