I am using this to check if fields are empty. The problem is, the error message is never thrown when a field is empty, it allows submission. Is it because I am trying to run onclick and onclientclick on the button? This is my syntax
HTML
<asp:Button ID="main1212" runat="server" Text="Check If JS Works"
OnClick="DoSomethingDoNothing_OnClick" OnClientClick="return ValidateData();" />
JS
<script type="text/javascript">
function ValidateData() {
var main1212, dropdownselection, dropdownselection1, field21
main1212 = document.getElementByID("txt313").value;
dropdownselection = document.getElementByID("dropdownlist1").value;
dropdownselection1 = document.getElementByID("dropdownlist11").value;
field21 = document.getElementByID("txt12").value;
if (main1212 == '')
{
alert("Error");
return false;
}
if (dropdownselection == '')
{
alert("Error");
return false;
}
if (dropdownlist1 == '')
{
alert("Error")
return false;
}
if (field21 == '')
{
alert("Error");
return false;
}}
</script>
EDIT
If I open the browser console and press the button that should run my script their are no errors displayed?
It's missing a semi-colon in this line (not sure) of the function ValidateData:
var main1212,dropdownselection,dropdownselection1,field21;
(it's good to avoid extra spaces and also not create variables for this)
And it could be more simple, or like this:
window.onload=function(){document.getElementById('main1212').onclick=function(){ValidateData();};}
Related
The email id is entered into a textbox and the validation for email is applied but there seems to be an error that the whole function is probably not called during execution
<head runat="server">
<title></title>
<script type="text/javascript">
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.Text %>');<!--textbox4 is used to receive the email entered by the user-->
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (textbox.value.length > 0)<!--the email field should be non empty-->
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");<!--incase of an invalid email-->
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" style="margin-left: 340px" Text="Submit" Width="96px" OnClick="Button1_Click1" OnClientClick="javascript:IsValidUrl();"/>
</form>
</body>``
There seems couple of issue with the javascript's IsValidURL function so please replace it with below code.
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.ID %>');
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (emailbox.value.length > 0)
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
There are mainly two problems
<%=TextBox4.Text %> here you want id of the textBox but you are fetching value of the textBox.
textbox.value.length you want to check value of the TextBox4 but its variable name is emailbox, not textbox.
So I have just corrected those.
Hope this helps you.
Probably your function is working correctly but the page gets submitted even after the validation so replace below:
OnClientClick="javascript:IsValidUrl();"
with
OnClientClick="return javascript:IsValidUrl();"
Edit
Just figured an error in your JS code if (textbox.value.length > 0) line should be if (emailbox.value.length > 0) so try with replace it.
Another issue I found in document.getElementById('<%=TextBox4.Text %>') which should be document.getElementById('<%=TextBox4.ID %>') and in case of using master pages it should be document.getElementById('<%=TextBox4.ClientID %>') so try replacing it too.
Hope this will help !!
function send() {
alert("Your message sent.");
}
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue != "" && messageValue != "") {
document.getElementById("af-form").submit();
} else {
alert("Nickname or message is blank. Please fill.");
return false;
}
}
These are my JS codes
<input type="text" name="nickname" id="input-nickname" required>
<textarea name="message" type="text" id="input-text" required></textarea>
<input type="submit" value="Send" onclick="wrongNickNameorMessage() + send()" />
And these are my HTML codes.
When I click on Send button. First alert("Your message sent."); then alert("nickname or message is blank. Please fill."); is working. Or exact opposite.
I wanna disabled send() function if wrongNickNameorMessage() is true.
How can I do that?
You have the right idea but you're going about it very out-of-the-way. Try this:
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue === "" || messageValue === "") {
alert("Nickname or message is blank or improper input detected. Please fill.");
return false;
}
document.getElementById("af-form").submit();
alert("Your message sent.");
}
You dont need the other function or the other part of the if statement since you're just validating input. You can get more creative but that's all you really need. Your function will completely stop if there's a problem but otherwise, it'll show the right message and submit.
Although your practice is horrible, this may help you in the future:
/* first give your submit button an id or something and don't use the onclick
attribute
*/
<input type='submit' value='Send' id='sub' />
// Now the JavaScript, which should be external for caching.
var doc = document;
// never have to use document.getElementById() again
function E(e){
return doc.getElementById(e);
}
function send() {
alert('Your message was sent.');
}
// put all your sub onclick stuff in here
E('sub').onclick = function(){
var nicknameValue = E('input-nickname').value;
var messageValue = E('input-text').value;
if(nicknameValue !== '' && messageValue !== '') {
send(); E('af-form').submit();
}
else {
alert('Nickname or message is blank. Please fill.');
return false;
}
}
Note, that this is not sufficient to handle a form. It just shows concept. JavaScript can be disabled, so you must account for that as well, Server Side.
You need to call a wrapper method that will call the wrongNickNameorMessage() check result and than continue only if returned true.
function conditionalSend(){if (wrongNickNameorMessage()){send();}}
I have a textbox and a button, on button's clientClick I call javascript function and there is also server side coding.
Problem is, the page gets post back even if I have return False in the javascript.
Here is my javascript function:
function checkALphaNumericFormat(str) {
//get previous value before editing
var txtUserId = document.getElementById('<%=txtUserId.ClientID%>');
var userId = txtUserId.value;
var patternAlphaNumeric = /^[A-z0-9]+$/gi;
var match = userId.match(patternAlphaNumeric);
//Check Null values
if (txtUserId.value != null && txtUserId.value != "") {
//Check for AlphaNumeric values for User Id
if (match == null) {
alert("Please provide valid AlphaNumeric User Id");
return false ;
}
return false ;
}
else {
alert("User Id field should not be null");
return false ;
}
return false ;
}
and I am calling this function on my Form as:
<asp:Button runat="server" ID="btnCreate" CssClass="loginButton" style="margin:0px 0px 1px 30px;" OnClientClick ="return checkALphaNumericFormat(this.value);" Text="CREATE" />
Try to call JavaScript function as below:
OnClientClick="if(!validateform()){return false;}
where validateform() should be your java script function. Your java script function should have return = true; at the end of function in successfull execution, like in below function:
function validateform()
{
var txtSearch = document.getElementById('<%=txtKeywordSearch.ClientID%>')
if(txtSearch.value == '')
{
alert('No Search Creatria Selected!');
return false;
}
return true;
}
Please try and let me know if it works for you.
Thanks,
Harish
function isGoodEmail() {
var email = document.getElementById("<%=txtComapnyEmail.ClientID%>").value;
if (email == "Email") {
if (window.isValidEmail(email)) {
if (/(aol|gmail|yahoo|hotmail)\.com$/.test(email)) {
alert(' valid email, but not for this site. No free service emails!');
return false;
}
return true;
}
return false;
}
Button code:
<asp:Button runat="server" class="button-orange" Text="Confirm and start my company page"
ID="Companystart" OnClick="CompanystartClick" OnClientClick="isGoodEmail" />
I am calling the above JavaScript from the button, but it is not validating the email. Even if entered gmail it is accepted.
use the following
<asp:Button runat="server" class="button-orange" Text="Confirm and start my company page"
ID="Companystart" OnClick="CompanystartClick" OnClientClick="return isGoodEmail()" />
Your are missing 'return' before your client click function call OnClientClick="return isGoodEmail()"
As you have written return true and false in your java-script so in your function call too there should be return before the function name.
For better understanding of return true and false you can go through this link
What's the effect of adding 'return false' to a click event listener?
---EDIT
function isGoodEmail() {
alert("In the beginning");
var email = document.getElementById("<%=txtComapnyEmail.ClientID%>").value;
alert(email);
if (email == "Email") {
if (window.isValidEmail(email)) {
if (/(aol|gmail|yahoo|hotmail)\.com$/.test(email)) {
alert(' valid email, but not for this site. No free service emails!');
return false;
}
return true;
}
return false;
}
If you put OnClientClick="return isGoodEmail()" it will work it invokes JavaScript code.
but suppose you put "gmail" as text for email, then the if condition
if (email == "Email")
is false so nothing is executed inside or returned
hence it feels like JavaScript is not invoked
try using firebug to debug and break-point js code
Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
$(".error").show(500);
}else{
$(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.