ErrorMessage "The field is required"

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • viki1967
    Contributor
    • Oct 2007
    • 263

    #1

    ErrorMessage "The field is required"

    Hello there.

    Here is my problem with this aspx page integrated with javascript function validator:
    1. I need show in the javascript alert the ErrorMessage "The field is required", when validations is enabled;
    2. The aspx page and my GridView is not updated after inserting interval DateStart and DateEnd, why?
    3. The aspx page and my GridView is not updated after inserting interval DateStart1 and DateEnd1, why?

    Can you help me?

    If you have link for similar task, please give it me.
    Can you explain any one or any sample code related this.

    Your help would be very appreciated.
    Thanks in advance for your time and hints.

    Cheers.
    Code:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="button.aspx.cs" Inherits="SqlServer_button" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
    </head>
    <body onload="InitValidators()">
        <form id="form1" runat="server">
        <div>
            <asp:ValidationSummary ID="ValidationSummary1" ShowMessageBox="true" runat="server"
                ShowSummary="false" />
            <asp:TextBox ID="DateStart" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DateStart"
                ErrorMessage="RequiredFieldValidator" Display="None"></asp:RequiredFieldValidator>
            <asp:TextBox ID="DateEnd" runat="server"></asp:TextBox>
            <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Not valid date!"
                ControlToValidate="DateEnd" ControlToCompare="DateStart" Type="Date" Operator="GreaterThanEqual"
                CssClass="redb" SetFocusOnError="false"></asp:CompareValidator>
            <asp:ImageButton ID="Button1" ImageUrl="images/cerca_icon.gif" runat="server" OnClick="Button1_Click"
                OnClientClick="javascript:InitValidators();return false;" />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DateEnd"
                ErrorMessage="RequiredFieldValidator" Display="None"></asp:RequiredFieldValidator>
            <br />
            <br />
            <asp:TextBox ID="DateStart1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="DateStart1"
                ErrorMessage="RequiredFieldValidator" Display="None"></asp:RequiredFieldValidator>
            <asp:TextBox ID="DateEnd1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="DateEnd1"
                ErrorMessage="RequiredFieldValidator" Display="None"></asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidator2" runat="server" ErrorMessage="Not valid date!"
                ControlToValidate="DateEnd1" ControlToCompare="DateStart1" Type="Date" Operator="GreaterThanEqual"
                CssClass="redb" SetFocusOnError="false"></asp:CompareValidator>
            <asp:ImageButton ID="Button2" ImageUrl="images/cerca_icon.gif" runat="server" OnClick="Button2_Click"
                OnClientClick="javascript:InitValidators();return false;" />
            <asp:Label ID="MessagesLabel" runat="server" Text=""></asp:Label>
            <br />
            <br />
        </div>
        </form>
        <script type="text/javascript" language="javascript">
            function InitValidators() {
    
                var DateStart = document.getElementById('<%=DateStart.ClientID%>');
                var DateEnd = document.getElementById('<%=DateEnd.ClientID%>')
                var DateStart1 = document.getElementById('<%=DateStart1.ClientID%>');
                var DateEnd1 = document.getElementById('<%=DateEnd1.ClientID%>')
    
                if (DateStart.value == '' || DateEnd.value == '') {
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator1.ClientID%>'), true);
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator2.ClientID%>'), true);
                }
                else {
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator1.ClientID%>'), false);
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator2.ClientID%>'), false);
                }
    
                if (DateStart1.value == '' || DateEnd1.value == '') {
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator3.ClientID%>'), true);
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator4.ClientID%>'), true);
                }
                else {
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator3.ClientID%>'), false);
                    ValidatorEnable(document.getElementById('<%= RequiredFieldValidator4.ClientID%>'), false);
                }
    
    
            }
        </script>
    </body>
    </html>
    Attached Files
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    #2
    I don't work with asp, but from the looks of your code, you may want to separate the form validation javaScript from the actions run on the server. That is not to say you should not validate your data on the server before processing.

    From your write up, it looks like you want to advise the user of missing data before the form is submitted. You can handle all that with javaScript no need for asp.

    You speak of a grid, so I assume you may have more date fields than what is shown in your code. You can write a generic validator to which you pass an object reference to the control being checked instead of writing one for each of the controls.

    One other recommendation would be to put all your javaScript in the header section of the html page.

    I suspect that your validator does not work because you are waiting until the page hits the server.

    Here is some old code that uses the "onChange" event handler. In today's modern code you may want to create a "change" eventlistener instead. But the code is a collection of control type validation, which may be useful to you in other ways.

    It is standalone code, so you can just copy it and test it. This code does not use an server intervention. You could modify the code to give more specific information in the alert box or alter the color of the control, or even show all errors at once. But at least the code gives focus to the control that needs to be corrected.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
      "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>Validator Routines</title>
    <script type="text/javascript">
    // validates that the field value string has one or more characters in it
    function isNotEmpty(elem) {
    	var str = elem.value;
        var re = /.+/;
        if(!str.match(re)) {
            alert("Please fill in the required field.");
            setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
            return false;
        } else {
            return true;
        }
    }
    //validates that the entry is a positive or negative number
    function isNumber(elem) {
    	var str = elem.value;
        var re = /^[-]?\d*\.?\d*$/;
        str = str.toString();
        if (!str.match(re)) {
            alert("Enter only numbers into the field.");
            setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
            return false;
        }
        return true;
    }
    // validates that the entry is 16 characters long
    function isLen16(elem) {
    	var str = elem.value;
        var re = /\b.{16}\b/;
        if (!str.match(re)) {
            alert("Entry does not contain the required 16 characters.");
            setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
            return false;
        } else {
            return true;
        }
    }
    // validates that the entry is formatted as an e-mail address
    function isEMailAddr(elem) {
    	var str = elem.value;
        var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
        if (!str.match(re)) {
            alert("Verify the e-mail address format.");
            setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
            return false;
        } else {
            return true;
        }
    }
    // validate that the user made a selection other than default
    function isChosen(select) {
        if (select.selectedIndex == 0) {
            alert("Please make a choice from the list.");
            return false;
        } else {
            return true;
        }
    }
    
    // validate that the user has checked one of the radio buttons
    function isValidRadio(radio) {
        var valid = false;
        for (var i = 0; i < radio.length; i++) {
            if (radio[i].checked) {
                return true;
            }
        }
        alert("Make a choice from the radio buttons.");
        return false;
    }
    
    function focusElement(formName, elemName) {
        var elem = document.forms[formName].elements[elemName];
        elem.focus();
        elem.select();
    }
    
    // batch validation router
    function validateForm(form) {
        if (isNotEmpty(form.name1)) {
            if (isNotEmpty(form.name2)) {
                if (isNotEmpty(form.eMail)) {
                    if (isEMailAddr(form.eMail)) {
                        if (isChosen(form.continent)) {
                            if (isValidRadio(form.accept)) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }
    </script>
    </head>
    <body>
    <h1>Form Validations</h1>
    <hr /> 
    <form method="GET" action=""
        name="sampleForm" onsubmit="return validateForm(this)">
    First Name: <input type="text" size="30" name="name1" id="name1" 
        onchange="isNotEmpty(this)" /><br>
    Last Name: <input type="text" size="30" name="name2" id="name2" 
        onchange="isNotEmpty(this)" /><br>
    E-mail Address: <input type="text" size="30" name="eMail" id="eMail" 
        onchange="if (isNotEmpty(this)) {isEMailAddr(this)}" /><br>
    Your Region: <select name="continent" id="continent">
        <option value="" selected>Choose One:</option>
        <option value="Africa">Africa</option>
        <option value="Asia">Asia</option>
        <option value="Australia">Australia/Pacific</option>
        <option value="Europe">Europe</option>
        <option value="North America">North America</option>
        <option value="South America">South America</option>
    </select><br>
    Licensing Terms: 
        <input type="radio" name="accept" id="accept1" value="agree" />I agree
        <input type="radio" name="accept" id="accept2" value="refuse" />I do not agree
    <br>
    <input type="reset" /> <input type="submit" />
    </form>
    </body>
    </html>

    Comment

    • ariful alam
      New Member
      • Jan 2011
      • 185

      #3
      To show a JavaScript Alert message you should validate your TextBox field in CodeBehind and on error you should register a JavaScript block to your .aspx page. It will show the message in JavaScript Alert message box.

      Comment

      • viki1967
        Contributor
        • Oct 2007
        • 263

        #4
        Problem fixed, thanks a lot for help.

        Comment

        Working...